C# Remove Invalid Characters from Filename

后端 未结 3 1865
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 23:14

I have data coming from an nvarchar field of the SQL server database via EF3.5. This string is used to create a Filename and need to remove invalid characters and tried foll

相关标签:
3条回答
  • 2021-01-07 23:25

    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);
    }
    
    0 讨论(0)
  • 2021-01-07 23:28

    no invalid chars returned by System.IO.Path.GetInvalidFileNameChars() being removed. – Bhuvan 5 mins ago

    The first method you posted works OK for the characters in Path.GetInvalidFileNameChars(), here it is at work:

    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:

    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/

    I again suspect that you'll see characters with codes larger than 128, and you should exclude those from your string.

    0 讨论(0)
  • 2021-01-07 23:37

    Try this

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

    0 讨论(0)
提交回复
热议问题