C # determine whether a file is a text file

Source: Internet
Author: User

I checked many pieces of data on the Internet. All the big data files were read as a binary file, and I took a single character segment, which is 255216 for example. jpg. The Code is as follows:

         /// <summary>
/// Checks the file is textfile or not.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public static FileExtension CheckTextFile(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
string fileType = string.Empty; ;
try
{
byte data = br.ReadByte();
fileType += data.ToString();
data = br.ReadByte();
fileType += data.ToString();
FileExtension extension;
try
{
extension = (FileExtension)Enum.Parse(typeof(FileExtension), fileType);
}
catch
{

extension=FileExtension.VALIDFILE
}
return extension;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
{
fs.Close();
br.Close();
}
}
}
}
public enum FileExtension
{
JPG = 255216,
GIF = 7173,
PNG = 13780,
SWF = 6787,
RAR = 8297,
ZIP = 8075,
_7Z = 55122,
VALIDFILE=9999999
// 255216 jpg;

// 7173 gif;

// 6677 bmp,

// 13780 png;

// 6787 swf

// 7790 exe dll,

// 8297 rar

// 8075 zip

// 55122 7z

// 6063 xml

// 6033 html

// 239187 aspx

// 117115 cs

// 119105 js

// 102100 txt

// 255254 sql

} <

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.