开发者

Remove invalid (disallowed, bad) characters from FileName (or Directory, Folder, File) [duplicate]

This question already has answers here: How to remove illegal characters from path and filenames? (30 answers) Closed 9 years ago.

I've wrote this little method to achieve the goal in the subj., however, is there more efficient (simpler) way of doing this? I hope this can help somebody who will search for this like I did.

var fileName = n开发者_开发百科ew System.Text.StringBuilder();
fileName.Append("*Bad/\ :, Filename,? ");
// get rid of invalid chars
while (fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > -1)
{
    fileName = fileName.Remove(fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()), 1);
}

?


I know this is a few years old but here is another solution for reference.

public string GetSafeFilename(string filename)
{

    return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));

}


Try the following

public string MakeValidFileName(string name) {
  var builder = new StringBuilder();
  var invalid = System.IO.Path.GetInvalidFileNameChars();
  foreach ( var cur in name ) {
    if ( !invalid.Contains(cur) ) {
      builder.Append(cur);
    }
  }
  return builder.ToString();
}


A different approach that is compatible with .NET 4. See my comments above explaining the need.

public static string ScrubFileName(string value)
{
   var sb = new StringBuilder(value);
   foreach (char item in Path.GetInvalidFileNameChars())
   {
      sb.Replace(item.ToString(), "");
   }
   return sb.ToString();
}


If you look for "concise" when you say simple:

public string StripInvalidChars(string filename) {
  return new String(
    filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray()
  );
}

That said, I'd go with JaredPar's solution. It's probably easier to read (depending on taste, background), my gut feeling is that it is more efficient (although I'm not sure how efficient you have to be stripping that dozen of invalid chars from a limited length filename) and his use of a StringBuilder() seems to fit perfectly to your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜