Building a directory string from component parts in C#

岁酱吖の 提交于 2019-12-01 04:45:25

Does C# support unlimited args in methods?

Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested):

string CombinePaths(params string[] parts) {
    string result = String.Empty;
    foreach (string s in parts) {
        result = Path.Combine(result, s);
    }
    return result;
}

LINQ to the rescue again. The Aggregate extension function can be used to accomplish what you want. Consider this example:

string[] ary = new string[] { "c:\\", "Windows", "System" };
string path = ary.Aggregate((aggregation, val) => Path.Combine(aggregation, val));
Console.WriteLine(path); //outputs c:\Windows\System

I prefer to use DirectoryInfo vs. the static methods on Directory, because I think it's better OO design. Here's a solution with DirectoryInfo + extension methods, that I think is quite nice to use:

    public static DirectoryInfo Subdirectory(this DirectoryInfo self, params string[] subdirectoryName)
    {
        Array.ForEach(
            subdirectoryName, 
            sn => self = new DirectoryInfo(Path.Combine(self.FullName, sn))
            );
        return self;
    }

I don't love the fact that I'm modifying self, but for this short method, I think it's cleaner than making a new variable.

The call site makes up for it, though:

        DirectoryInfo di = new DirectoryInfo("C:\\")
            .Subdirectory("Windows")
            .Subdirectory("System32");

        DirectoryInfo di2 = new DirectoryInfo("C:\\")
            .Subdirectory("Windows", "System32");

Adding a way to get a FileInfo is left as an exercise (for another SO question!).

Try this one:

public static string CreateDirectoryName(string fileName, params string[] folders)
{
    if(folders == null || folders.Length <= 0)
    {
        return fileName;
    }

    string directory = string.Empty;
    foreach(string folder in folders)
    {
        directory = System.IO.Path.Combine(directory, folder);
    }
    directory = System.IO.Path.Combine(directory, fileName);

    return directory;
}

The params makes it so that you can append an infinite amount of strings.

Path.Combine does is to make sure that the inputted strings does not begin with or ends with slashes and checks for any invalid characters.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!