title: How can I know if a file is a txt or binary using its content?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/910873/how-can-i-determine-if-a-file-is-binary-or-text-in-c">How can I determine if a file is binary or text in c#?</a>  </p>
  </blockquote>
  
  
  
  <p>Without consider the filename (the extension), using only the content, we need to know if a file is text or binary. I can’t use the extension because I don’t know all the text file extensions, and because a text file can be without extension.</p>
  
  <p>I was doing it looking for the percentage of the non -ASCII bytes  in the first part of the file. I cannot read the full file each time for performance reasons. I was using the following code:</p>
  
  <pre><code>private static bool IsBinary(byte[] bytes, int maxLength)
  {
      int len = maxLength &gt; 1024 ? 1024 : maxLength;
  
      int nonASCIIcount = 0;
  
      for( int i = 0; i &lt; len; ++i )
          if( bytes[i] &gt; 127 )
              ++nonASCIIcount;
  
      // if the number of non ASCII is more than a 30%
      // then is a binary file. 
      return (nonASCIIcount / len) &gt; 0.3;
  }
  </code></pre>
  
  <p>The problem is that some kinds of files are wrongly detected as text because the first part of the file is text like photoshop files.</p>
  
  <p>Any suggestion?</p>