我有来自SQL Server数据库的nvarchar字段的数据通过EF3.5.此字符串用于创建文件名,需要删除无效字符并尝试以下选项,但它们都不起作用.请提出为什么这是一个可以理解的谜团?我做错了吗?
我浏览了本网站上的几乎所有相关问题..现在发布了来自其他类似问题的所有建议/答案的综合问题.
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;
}
Run Code Online (Sandbox Code Playgroud)
Gar*_*del 27
这是我在静态公共类中使用的函数:
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);
}
Run Code Online (Sandbox Code Playgroud)
\n\n\n没有删除 System.IO.Path.GetInvalidFileNameChars() 返回的无效字符。\xe2\x80\x93 Bhuvan 5 分钟前
\n
您发布的第一种方法对于 中的字符工作正常Path.GetInvalidFileNameChars(),在这里它起作用了:
static void Main(string[] args)\n{\n string input = "abc<def>ghi\\\\1234/5678|?9:*0";\n\n string output = CleanFileName1(input);\n\n Console.WriteLine(output); // this prints: abcdefghi1234567890\n\n Console.Read();\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我想你的问题是一些特定于语言的特殊字符。您可以尝试通过打印字符串中字符的 ASCII 代码来解决此问题:
\n\nstring stringFromDatabase = "/5678|?9:*0"; // here you get it from the database\n\nforeach (char c in stringFromDatabase.ToCharArray())\n Console.WriteLine((int)c);\nRun Code Online (Sandbox Code Playgroud)\n\n并查阅 ASCII 表:http://www.asciitable.com/
\n\n我再次怀疑您会看到代码大于 128 的字符,您应该从字符串中排除这些字符。
\n