问题描述
我正在尝试迭代本地目录中的文件:
foreach(Directory.GetFileSystemEntries(path)中的字符串名称)
{
FileAttrtibutes att = File.GetAttributes(name)
}
路径
文件夹中的一个文件名为This is a test。 GetAttributes()
在带空格的文件名上抛出异常。
除了用其他字符替换空格外,应如何处理在这种情况下我处理文件名中的空格?
我道歉。我有点仓促。让我重新定义问题,即使我现在至少有一个解决方法。
这段代码显示了问题:
Uri u = new Uri(@file:/// c:/ test / This is a test);
FileAttributes a = File.GetAttributes(u.AbsolutePath);
File.GetAttributes抛出System.IO.FileNotFoundException:找不到文件'c:\ test \This%图20是%20A%20test。 'c:\ test \这是一个测试'存在。
所以看来Uri.AbsolutePath正在插入%20空格,我只能做一个字符串替换以使我的代码工作。我不知道我应该期待更换,但至少我可以让它工作。欢迎任何其他想法。
我也遇到了类似的问题。
.Replace(%20,)
var assemblyPath = new Uri(Assembly.GetExecutingAssembly()。CodeBase).AbsolutePath.Replace(%20,);
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.
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", " ");
这篇关于如何处理文件名中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!