从 C# 中的组件构建目录字符串

发布于 2024-07-06 02:53:16 字数 405 浏览 7 评论 0原文

如果我有很多目录名称作为文字字符串或包含在变量中,那么将它们组合起来形成完整路径的最简单方法是什么?

我知道

Path.Combine
but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.

例如:

string folder1 = "foo";
string folder2 = "bar";

CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")

有什么想法吗? C# 是否支持方法中的无限参数?

If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?

I know of

Path.Combine

but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.

e.g:

string folder1 = "foo";
string folder2 = "bar";

CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")

Any ideas?
Does C# support unlimited args in methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浴红衣 2024-07-13 02:53:17

C# 是否支持方法中的无限参数?

是的,看看 params 关键字。 可以轻松编写一个仅调用 Path.Combine 适当次数的函数,如下所示(未经测试):

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

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;
}
巷雨优美回忆 2024-07-13 02:53:17

LINQ 再次来救援。 Aggregate 扩展函数可用于完成你想要的。 考虑这个例子:

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

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
极度宠爱 2024-07-13 02:53:17

与 Directory 上的静态方法相比,我更喜欢使用 DirectoryInfo,因为我认为这是更好的 OO 设计。 这是一个使用 DirectoryInfo + 扩展方法的解决方案,我认为使用起来非常好:

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

我不喜欢修改 self 的事实,但对于这个简短的方法,我认为它比创建一个新变量。

不过,调用站点弥补了这一点:

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

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

添加一种获取 FileInfo 的方法留作练习(对于另一个 SO 问题!)。

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

谁人与我共长歌 2024-07-13 02:53:17

试试这个:

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

参数使您可以附加无限数量的字符串。

Path.Combine 的作用是确保输入的字符串不以斜杠开头或结尾,并检查是否有任何无效字符。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文