3

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.

JeffR
  • 828
  • 1
  • 13
  • 22

2 Answers2

0

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.

string.Empty
  • 10,393
  • 4
  • 39
  • 67
0

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", " ");
Mystic Lin
  • 365
  • 4
  • 15