如何处理文件名中的空格 [英] How to deal with spaces in filenames

查看:211
本文介绍了如何处理文件名中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试迭代本地目录中的文件:

  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", " ");

这篇关于如何处理文件名中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆