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

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

    I needed to do this today... in my case, I needed to concatenate a customer name with the date and time for a final .kmz file. My final solution was this:

     string name = "Whatever name with valid/invalid chars";
     char[] invalid = System.IO.Path.GetInvalidFileNameChars();
     string validFileName = string.Join(string.Empty,
                                string.Format("{0}.{1:G}.kmz", name, DateTime.Now)
                                .ToCharArray().Select(o => o.In(invalid) ? '_' : o));
    

    You can even make it replace spaces if you add the space char to the invalid array.

    Maybe it's not the fastest, but as performance wasn't an issue, I found it elegant and understandable.

    Cheers!

提交回复
热议问题