title: C# Remove Invalid Characters from Filename
body: <p>I have data coming from an nvarchar field of the SQL server database via EF3.5. This string is used to create a Filename and need to remove invalid characters and tried following options but none of them works. Please suggest why this is such an understandable mystery? Am I doing anything wrong? </p>
  
  <p>I went though almost all of the related questions on this site.. and now posting a consolidated question from all the suggestions/answers from other similar questions.</p>
  
  <p>UPD: The Issue was unrelated..All of these options do work. So posting it to community wiki.</p>
  
  <pre><code>public static string CleanFileName1(string filename)
  {            
      string file = filename;                                            
      file = string.Concat(file.Split(System.IO.Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));
  
      if (file.Length &gt; 250)
      {
          file = file.Substring(0, 250);
      }
      return file;
   }
  
  public static string CleanFileName2(string filename)
  {
      var builder = new StringBuilder();
      var invalid = System.IO.Path.GetInvalidFileNameChars();
      foreach (var cur in filename)
      {
          if (!invalid.Contains(cur))
          {
              builder.Append(cur);
          }
      }
      return builder.ToString();
  }
  
  public static string CleanFileName3(string filename)
  {                                    
      string regexSearch = string.Format("{0}{1}",
          new string(System.IO.Path.GetInvalidFileNameChars()),
          new string(System.IO.Path.GetInvalidPathChars()));
      Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
      string file = r.Replace(filename, "");
  
      return file;
  }       
  
  public static string CleanFileName4(string filename)
  {
      return new String(filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray());
  }   
  
  public static string CleanFileName5(string filename)
  {            
      string file = filename;
  
      foreach (char c in System.IO.Path.GetInvalidFileNameChars())
      {
          file = file.Replace(c, '_');
      }                                 
      return file;
  }   
  </code></pre>