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

后端 未结 14 1073
伪装坚强ぢ
伪装坚强ぢ 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:15

    A simple one line code:

    var validFileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (f, c) => f.Replace(c, '_'));
    

    You can wrap it in an extension method if you want to reuse it.

    public static string ToValidFileName(this string fileName) => Path.GetInvalidFileNameChars().Aggregate(fileName, (f, c) => f.Replace(c, '_'));
    

提交回复
热议问题