简体   繁体   English

在名称包含空格的文件夹中使用C#处理文件

[英]Processing files with C# in folders whose names contain spaces

There are plenty of C# samples that show how to manipulate files and directories but they inevitably use folder paths that contain no spaces. 有许多C#示例显示如何处理文件和目录,但它们不可避免地使用不包含空格的文件夹路径。 In the real world I need to be able to process files in folders with names that contain spaces. 在现实世界中,我需要能够处理名称包含空格的文件夹中的文件。 I have written the code below which shows how I have solved the problem. 我在下面编写了代码,显示了如何解决该问题。 However it doesn't seem to be very elegant and I wonder if anyone has a better way. 但是,它似乎并不十分优雅,我想知道是否有人有更好的方法。

    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();
    }
}

Regards, Nigel Ainscoe 问候,奈杰尔·恩斯科

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

or: 要么:

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM