2010-05-08 77 views
0

有大量C#示例显示如何操作文件和目录,但它们不可避免地使用不包含空格的文件夹路径。在现实世界中,我需要能够处理名称中包含空格的文件夹中的文件。我写下面的代码显示了我如何解决问题。然而,它似乎不是很优雅,我想知道是否有人有更好的方法。用C#处理名称中包含空格的文件夹中的文件

class Program 
{ 
    static void Main(string[] args) 
    { 

     var dirPath = @args[0] + "\\"; 

     string[] myFiles = Directory.GetFiles(dirPath, "*txt"); 
     foreach (var oldFile in myFiles) 
     { 
      string newFile = dirPath + "New " + Path.GetFileName(oldFile); 
      File.Move(oldFile, newFile); 
     } 
     Console.ReadKey(); 
    } 
} 

问候, 奈杰尔Ainscoe

+3

使用Path.Combine(),而不是用反斜杠自己处理的... – 2010-05-08 17:29:36

+0

我缺少的东西?所有的'System.IO'类都用空格处理文件和目录。从技术上讲,即使是DOS,在文件系统方面,只是某些命令行工具没有正确解析空格。 – Aaronaught 2010-05-08 17:37:15

+0

Path.Combine是至关重要的 - 如果你尝试自己做斜杠并且在你尝试一个带空格的文件之前不会意识到,你会得到一个错误 – stuartdotnet 2014-01-20 09:27:43

回答

1
string newFile = Path.Combine(args[0], "New " + Path.GetFileName(oldFile)); 

或:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Directory 
      .GetFiles(args[0], "*txt") 
      .ToList() 
      .ForEach(oldFile => { 
       var newFile = Path.Combine(
        Path.GetDirectoryName(oldFile), 
        "New " + Path.GetFileName(oldFile) 
       ); 
       File.Move(oldFile, newFile); 
      }); 
     Console.ReadKey(); 
    } 
} 
+0

看起来更像是Darin之后的东西。谢谢。 – 2010-05-08 17:40:57

+0

现在我只需要检查用户传递的路径不包含尾部反斜杠否则它崩溃 – 2010-05-08 17:46:12

相关问题