开发者

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. 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜