在C#号楼从零部件目录字符串 [英] Building a directory string from component parts in C#

查看:90
本文介绍了在C#号楼从零部件目录字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有很多的目录名或作为文字字符串或包含的变量,什么是结合这些构成一个完整路径的最简单的方法是什么?



我知道的

 Path.Combine 

但这只需要2个字符串参数,我需要,可以采取的目录参数任意数量的数字解决方案。



例如:

 
字符串文件夹1 =富;
字符串文件夹2 =酒吧;

CreateAPath(C:,文件夹1,文件夹2,文件夹1,文件夹1,文件夹2,MyFile.txt的)

任何想法?
则C#支持无限ARGS的方法?


解决方案

请问C#支持无限ARGS中方法是什么?




是的,有看params关键字。将可以很容易地编写一个函数,只是调用Path.Combine的适当次数,像这样(未经):

 字符串CombinePaths(PARAMS字符串[]部分){
字符串结果=的String.Empty;
的foreach(字符串s的部分){
结果= Path.Combine(结果,S);
}
返回结果;
}


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?

解决方案

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

这篇关于在C#号楼从零部件目录字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆