开发者

Processing files with C# in folders whose names contain spaces

开发者 https://www.devze.com 2022-12-29 09:44 出处:网络
There are plenty of C# samples that show how to manipulate files and directories but they inevitably use folder paths that contain no spaces. In the real world I need to be able to process files in fo

There are plenty of C# samples that show how to manipulate files and directories but they inevitably use folder paths that contain no spaces. In the real world I need to be able to process files in folders with names that contain space开发者_如何学Pythons. 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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号