简体   繁体   English

C#从Filename中删除无效字符

[英]C# Remove Invalid Characters from Filename

I have data coming from an nvarchar field of the SQL server database via EF3.5. 我有来自SQL Server数据库的nvarchar字段的数据通过EF3.5。 This string is used to create a Filename and need to remove invalid characters and tried following options but none of them works. 此字符串用于创建文件名,需要删除无效字符并尝试以下选项,但它们都不起作用。 Please suggest why this is such an understandable mystery? 请提出为什么这是一个可以理解的谜团? Am I doing anything wrong? 我做错了吗?

I went though almost all of the related questions on this site.. and now posting a consolidated question from all the suggestions/answers from other similar questions. 我浏览了本网站上的几乎所有相关问题..现在发布了来自其他类似问题的所有建议/答案的综合问题。

UPD: The Issue was unrelated..All of these options do work. UPD:问题无关......所有这些选项都有效。 So posting it to community wiki. 所以将其发布到社区维基。

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

Here is a function I use in a static common class: 这是我在静态公共类中使用的函数:

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)

no invalid chars returned by System.IO.Path.GetInvalidFileNameChars() being removed. 没有被删除的System.IO.Path.GetInvalidFileNameChars()返回的无效字符。 – Bhuvan 5 mins ago - Bhuvan 5分钟前

The first method you posted works OK for the characters in Path.GetInvalidFileNameChars() , here it is at work: 你发布的第一个方法适用于Path.GetInvalidFileNameChars()的字符,这里它正在工作:

static void Main(string[] args)
{
    string input = "abc<def>ghi\\1234/5678|?9:*0";

    string output = CleanFileName1(input);

    Console.WriteLine(output); // this prints: abcdefghi1234567890

    Console.Read();
}

I suppose though that your problem is with some language-specific special characters. 我想虽然你的问题是一些语言特定的特殊字符。 You can try to troubleshoot this problem by printing out the ASCII codes of the characters in your string: 您可以尝试通过打印字符串中字符的ASCII代码来解决此问题:

string stringFromDatabase = "/5678|?9:*0"; // here you get it from the database

foreach (char c in stringFromDatabase.ToCharArray())
    Console.WriteLine((int)c);

and consulting the ASCII table: http://www.asciitable.com/ 并查阅ASCII表: http//www.asciitable.com/

I again suspect that you'll see characters with codes larger than 128, and you should exclude those from your string. 再次怀疑你会看到代码大于128的字符,你应该从字符串中排除这些字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM