通过文件头来检查文件的类型

/// <summary>
/// 通过文件头来检查文件的类型
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static bool CheckFileHead(string filePath)
{
var fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
var r = new BinaryReader(fs);
string fileclass = "";
try
{
byte buffer = r.ReadByte();
fileclass = buffer.ToString(CultureInfo.InvariantCulture);
buffer = r.ReadByte();
fileclass += buffer.ToString(CultureInfo.InvariantCulture);
}
catch
{
System.IO.File.Delete(filePath);
return false;
}
r.Close();
fs.Close();
bool check = (fileclass == "8075" || fileclass == "208207");
if (!check)
{
System.IO.File.Delete(filePath);
}
return check;
}

原文地址:https://www.cnblogs.com/isdavid/p/3217204.html