How to remove illegal characters from path and filenames?

前端 未结 29 2872
离开以前
离开以前 2020-11-22 17:18

I need a robust and simple way to remove illegal path and file characters from a simple string. I\'ve used the below code but it doesn\'t seem to do anything, what am I miss

29条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 17:36

    Here is a function which replaces all illegal characters in a file name by a replacement character:

    public static string ReplaceIllegalFileChars(string FileNameWithoutPath, char ReplacementChar)
    {
      const string IllegalFileChars = "*?/\\:<>|\"";
      StringBuilder sb = new StringBuilder(FileNameWithoutPath.Length);
      char c;
    
      for (int i = 0; i < FileNameWithoutPath.Length; i++)
      {
        c = FileNameWithoutPath[i];
        if (IllegalFileChars.IndexOf(c) >= 0)
        {
          c = ReplacementChar;
        }
        sb.Append(c);
      }
      return (sb.ToString());
    }
    

    For example the underscore can be used as a replacement character:

    NewFileName = ReplaceIllegalFileChars(FileName, '_');
    

提交回复
热议问题