gpt4 book ai didi

C# 从文件名中删除无效字符

转载 作者:可可西里 更新时间:2023-11-01 03:14:02 25 4
gpt4 key购买 nike

我有通过 EF3.5 来自 SQL Server 数据库的 nvarchar 字段的数据。此字符串用于创建文件名,需要删除无效字符并尝试了以下选项,但均无效。请提出为什么这是一个可以理解的谜团?我做错了什么吗?

我浏览了该站点上几乎所有相关问题.. 现在发布了一个来自其他类似问题的所有建议/答案的综合问题。

UPD:问题无关..所有这些选项都有效。所以将其发布到社区维基。

public static string CleanFileName1(string filename)
{
string file = filename;
file = string.Concat(file.Split(System.IO.Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));

if (file.Length > 250)
{
file = file.Substring(0, 250);
}
return file;
}

public static string CleanFileName2(string filename)
{
var builder = new StringBuilder();
var invalid = System.IO.Path.GetInvalidFileNameChars();
foreach (var cur in filename)
{
if (!invalid.Contains(cur))
{
builder.Append(cur);
}
}
return builder.ToString();
}

public static string CleanFileName3(string filename)
{
string regexSearch = string.Format("{0}{1}",
new string(System.IO.Path.GetInvalidFileNameChars()),
new string(System.IO.Path.GetInvalidPathChars()));
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
string file = r.Replace(filename, "");

return file;
}

public static string CleanFileName4(string filename)
{
return new String(filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray());
}

public static string CleanFileName5(string filename)
{
string file = filename;

foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
file = file.Replace(c, '_');
}
return file;
}

最佳答案

这是我在静态公共(public)类中使用的一个函数:

public static string RemoveInvalidFilePathCharacters(string filename, string replaceChar)
{
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
return r.Replace(filename, replaceChar);
}

关于C# 从文件名中删除无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3825433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com