Csharp/C#教程:C#从Filename中删除无效字符分享


C#从Filename中删除无效字符

我有来自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; } 

没有被删除的System.IO.Path.GetInvalidFileNameChars()返回的无效字符。 – Bhuvan 5分钟前

您发布的第一个方法适用于Path.GetInvalidFileNameChars()的字符,这里它正在工作:

 static void Main(string[] args) { string input = "abcghi\1234/5678|?9:*0"; string output = CleanFileName1(input); Console.WriteLine(output); // this prints: abcdefghi1234567890 Console.Read(); } 

我想虽然你的问题是一些语言特定的特殊字符。 您可以尝试通过打印字符串中字符的ASCII代码来解决此问题:

 string stringFromDatabase = "/5678|?9:*0"; // here you get it from the database foreach (char c in stringFromDatabase.ToCharArray()) Console.WriteLine((int)c); 

并查阅ASCII表: http : //www.asciitable.com/

再次怀疑你会看到代码大于128的字符,你应该从字符串中排除这些字符。

这是我在静态公共类中使用的函数:

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

试试这个

filename = Regex.Replace(filename, "[/?:*""><|]+", "", RegexOptions.Compiled)

上述就是C#学习教程:C#从Filename中删除无效字符分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1029477.html

(0)
上一篇 2022年1月12日
下一篇 2022年1月12日

精彩推荐