Replacing delimiter characters in file path

余生颓废 提交于 2019-12-05 14:24:02

For a start, calling fullpath.Replace() does nothing to fullpath; it returns a new string. Also, when your string literals have a \ (backslash) in them, you need to tell the compiler that you're not trying to use an escape sequence:

fullpath = fullpath.Replace(@"\\", @"\"); 

The @ means "please treat this string literally (verbatim)". In other words, "when I say backslash, I mean backslash!"

See http://msdn.microsoft.com/en-us/library/362314fe.aspx.

Edit:

As LeBleu mentioned, you are calling Directory.Exists() on a full filepath. This won't work; you need to extract the directory part from the path. Try this:

if (!Directory.Exists(Path.GetDirectoryName(fullpath)))
{
     ...
}

Are you sure the problem is the backslashes? Backslash is an escape character in strings, such that if you were adding it in a string you have to type it as "\\" rather than "\". (if you don't use @) Note that the debugger frequently displays the string the way you would put it in code, with the escape characters, rather than direct.

According to the documentation, Page.Request.PhysicalPath returns the path to the specific file you are in, not the directory. Directory.Exists is only true if you give it a directory, not a file. Does File.Exists() return true?

You might want to consider replacing it with the Path.DirectorySeparatorChar rather than \ on the offchance that your code may end up running on a different platform one day (mono.net allows it to be run on linux or possibly more likely it might end up on some wierd mobile platform)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!