How to remove illegal characters from path and filenames?

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

    You can remove illegal chars using Linq like this:

    var invalidChars = Path.GetInvalidFileNameChars();
    
    var invalidCharsRemoved = stringWithInvalidChars
    .Where(x => !invalidChars.Contains(x))
    .ToArray();
    

    EDIT
    This is how it looks with the required edit mentioned in the comments:

    var invalidChars = Path.GetInvalidFileNameChars();
    
    string invalidCharsRemoved = new string(stringWithInvalidChars
      .Where(x => !invalidChars.Contains(x))
      .ToArray());
    

提交回复
热议问题