How to remove illegal characters from path and filenames?

前端 未结 29 3397
离开以前
离开以前 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:29

    The original question asked to "remove illegal characters":

    public string RemoveInvalidChars(string filename)
    {
        return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));
    }
    

    You may instead want to replace them:

    public string ReplaceInvalidChars(string filename)
    {
        return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));    
    }
    

    This answer was on another thread by Ceres, I really like it neat and simple.

提交回复
热议问题