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

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

    fileName = fileName.Replace(":", "-") 
    

    However ":" is not the only illegal character for Windows. You will also have to handle:

    /, \, :, *, ?, ", <, > and |
    

    These are contained in System.IO.Path.GetInvalidFileNameChars();

    Also (on Windows), "." cannot be the only character in the filename (both ".", "..", "...", and so on are invalid). Be careful when naming files with ".", for example:

    echo "test" > .test.
    

    Will generate a file named ".test"

    Lastly, if you really want to do things correctly, there are some special file names you need to look out for. On Windows you can't create files named:

    CON, PRN, AUX, CLOCK$, NUL
    COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9
    LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.
    

提交回复
热议问题