How to deal with spaces in filenames

浪子不回头ぞ 提交于 2020-01-15 05:41:46

问题


I am trying to iterate over files in a local directory:

foreach (string name in Directory.GetFileSystemEntries(path))
{
    FileAttrtibutes att = File.GetAttributes(name)
}

One of the files in the folder at path is named "This is a test". GetAttributes() throws an exception on filenames with spaces.

Apart from replacing spaces with some other character, how should I handle spaces in filenames in this circumstance?

I apologise. I was a bit hasty. Let me redefine the problem, even though I now have a workaround at least.

This snippet of code shows the problem:

Uri u = new Uri(@"file:///c:/test/This is a test");
FileAttributes a = File.GetAttributes(u.AbsolutePath);

File.GetAttributes throws a System.IO.FileNotFoundException: Could not find file 'c:\test\This%20is%20a%20test'. 'c:\test\This is a test' exists.

So it seems Uri.AbsolutePath is inserting %20 for space, and I can just do a string replace to get my code working. I don't know that I should expect to have to do the replace, but at least I can get it working. Any other ideas welcome.


回答1:


According to MSDN these are the possible exceptions,

ArgumentException
path is empty, contains only white spaces, or contains invalid characters.

PathTooLongException
The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

NotSupportedException
path is in an invalid format.

FileNotFoundException
path represents a file and is invalid, such as being on an unmapped drive, or the file cannot be found.

DirectoryNotFoundException
path represents a directory and is invalid, such as being on an unmapped drive, or the directory cannot be found.

IOException
This file is being used by another process.

UnauthorizedAccessException
The caller does not have the required permission.

Since you are looping through entries in a directory, the only guess i could make without you telling us the exception, is that either the file is being used by another process or your app doesn't have permission to the file.




回答2:


I also encountered a similar problem.

That's my stupid solution: Just add .Replace("%20", " ")

var assemblyPath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath.Replace("%20", " ");


来源:https://stackoverflow.com/questions/23237924/how-to-deal-with-spaces-in-filenames

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