我正在编写一个 C# 程序,它从文件中读取某些标签,并根据标签值创建一个目录结构。
现在这些标签里可能有任何东西,
如果标签名称不适合目录名称,我必须通过用任何合适的字符替换这些字符来准备它以使其适合。这样目录创建就不会失败。我正在使用以下代码,但我意识到这还不够..
path = path.replace("/","-");
path = path.replace("\\","-");
请告知最好的方法是什么..
谢谢,
我正在编写一个 C# 程序,它从文件中读取某些标签,并根据标签值创建一个目录结构。
现在这些标签里可能有任何东西,
如果标签名称不适合目录名称,我必须通过用任何合适的字符替换这些字符来准备它以使其适合。这样目录创建就不会失败。我正在使用以下代码,但我意识到这还不够..
path = path.replace("/","-");
path = path.replace("\\","-");
请告知最好的方法是什么..
谢谢,
导入 System.IO 命名空间并用于路径使用
Path.GetInvalidPathChars
并用于文件名
Path.GetInvalidFileNameChars
例如
string filename = "salmnas dlajhdla kjha;dmas'lkasn";
foreach (char c in Path.GetInvalidFileNameChars())
filename = filename.Replace(System.Char.ToString(c), "");
foreach (char c in Path.GetInvalidPathChars())
filename = filename.Replace(System.Char.ToString(c), "");
然后你可以使用 Path.Combine 添加标签来创建路径
string mypath = Path.Combine(@"C:\", "First_Tag", "Second_Tag");
//return C:\First_Tag\Second_Tag
您可以在此处使用无效字符的完整列表来根据需要处理替换。这些可通过Path.GetInvalidFileNameChars和Path.GetInvalidPathChars方法直接获得。
您现在必须使用的字符是:? < > | : \ / * "
string PathFix(string path)
{
List<string> _forbiddenChars = new List<string>();
_forbiddenChars.Add("?");
_forbiddenChars.Add("<");
_forbiddenChars.Add(">");
_forbiddenChars.Add(":");
_forbiddenChars.Add("|");
_forbiddenChars.Add("\\");
_forbiddenChars.Add("/");
_forbiddenChars.Add("*");
_forbiddenChars.Add("\"");
for (int i = 0; i < _forbiddenChars.Count; i++)
{
path = path.Replace(_forbiddenChars[i], "");
}
return path;
}
提示:不能包含双引号 ( "
),但可以包含 2 个引号 ( ''
)。在这种情况下:
string PathFix(string path)
{
List<string> _forbiddenChars = new List<string>();
_forbiddenChars.Add("?");
_forbiddenChars.Add("<");
_forbiddenChars.Add(">");
_forbiddenChars.Add(":");
_forbiddenChars.Add("|");
_forbiddenChars.Add("\\");
_forbiddenChars.Add("/");
_forbiddenChars.Add("*");
//_forbiddenChars.Add("\""); Do not delete the double-quote character, so we could replace it with 2 quotes (before the return).
for (int i = 0; i < _forbiddenChars.Count; i++)
{
path = path.Replace(_forbiddenChars[i], "");
}
path = path.Replace("\"", "''"); //Replacement here
return path;
}
您当然会只使用其中之一(或将它们组合成一个带有 bool 参数的函数来替换引号,如果需要)
Nikhil Agrawal的正确答案有一些语法错误。
仅供参考,这里是一个编译版本:
public static string MakeValidFolderNameSimple(string folderName)
{
if (string.IsNullOrEmpty(folderName)) return folderName;
foreach (var c in System.IO.Path.GetInvalidFileNameChars())
folderName = folderName.Replace(c.ToString(), string.Empty);
foreach (var c in System.IO.Path.GetInvalidPathChars())
folderName = folderName.Replace(c.ToString(), string.Empty);
return folderName;
}