How to make a valid Windows filename from an arbitrary string?

后端 未结 14 1117
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 02:50

I\'ve got a string like \"Foo: Bar\" that I want to use as a filename, but on Windows the \":\" char isn\'t allowed in a filename.

Is there a method that will turn \

14条回答
  •  心在旅途
    2020-12-23 03:26

    Cleaning a little my code and making a little refactoring... I created an extension for string type:

    public static string ToValidFileName(this string s, char replaceChar = '_', char[] includeChars = null)
    {
      var invalid = Path.GetInvalidFileNameChars();
      if (includeChars != null) invalid = invalid.Union(includeChars).ToArray();
      return string.Join(string.Empty, s.ToCharArray().Select(o => o.In(invalid) ? replaceChar : o));
    }
    

    Now it's easier to use with:

    var name = "Any string you want using ? / \ or even +.zip";
    var validFileName = name.ToValidFileName();
    

    If you want to replace with a different char than "_" you can use:

    var validFileName = name.ToValidFileName(replaceChar:'#');
    

    And you can add chars to replace.. for example you dont want spaces or commas:

    var validFileName = name.ToValidFileName(includeChars: new [] { ' ', ',' });
    

    Hope it helps...

    Cheers

提交回复
热议问题