title: asp.net mvc file download --System.FormatException: An invalid character was found in the mail header
body: <p>Our website has files in a few different languages - French, Spanish, Portuguese, and English. When a user uploads a file that contains special characters like ó or ç or ã etc i get an error message when i return <code>File(data, "application/octet-stream", name);</code> in MVC i get the exception:</p>
  
  <pre><code>System.FormatException: An invalid character was found in the mail header.
  </code></pre>
  
  <p>I found an article in MSDN for this showing how to set the mailmessage to UTF-8 encoding to avoid this. But i do not know how to UTF-8 encode the filename when using the MVC file actionresult. I found an article on the net to UTF-8 encode a string but when I try to use it I get a garbage name so I guess I do not understand what UTF-8 encoding is supposed to do to the string. Here is the sample code found in this blog post: <a href="http://codeharder.com/post/An-invalid-character-was-found-in-the-mail-header.aspx" rel="nofollow noreferrer">An invalid character was found in the mail header</a> </p>
  
  <pre><code> public static string GetCleanedFileName(string s)
      {
  
          char[] chars = s.ToCharArray();
  
          var sb = new StringBuilder();
  
          for (int index = 0; index &lt; chars.Length; index++)
          {
              string encodedString = EncodeChar(chars[index]);
              sb.Append(encodedString);
          }
          return sb.ToString();
      }
  
  
      private static string EncodeChar(char chr)
      {
  
          var encoding = new UTF8Encoding();
  
          var sb = new StringBuilder();
  
          byte[] bytes = encoding.GetBytes(chr.ToString());
  
          for (int index = 0; index &lt; bytes.Length; index++)
          {
              sb.AppendFormat("%{0}", Convert.ToString(bytes[index], 16));
          }
          return sb.ToString();
      } 
  </code></pre>