[C#] 判斷檔案類型(非副檔名判斷)
本帖最後由 whitefox 於 2023-6-1 13:17 編輯可能一般判斷檔案類型時直覺以副檔名為主
但實際真正判斷此檔案屬於哪一類是用檔案開頭的資訊來判斷
在維基百科上可以查到各種類型檔案的檔頭規範,關鍵字是『File Signatures』
List of file signatures
以下用C#程式來實現區分的功能public static void CheckTrueFileName()
{
string path =@"C:\Test.doc";
System.IO.FileStream fs = newSystem.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = newSystem.IO.BinaryReader(fs);
string bx =" ";
byte buffer;
try
{
buffer = r.ReadByte();
bx = buffer.ToString();
buffer = r.ReadByte();
bx += buffer.ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
r.Close();
fs.Close();
// 真實的檔案型別
Console.WriteLine(bx);
//檔名,包括格式
Console.WriteLine(System.IO.Path.GetFileName(path));
//檔名,不包括格式
Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(path));
//檔案格式
Console.WriteLine(System.IO.Path.GetExtension(path));
Console.ReadLine();
}以下列舉幾種類型的檔頭資訊public enum FileExtension
{
JPG =255216,
GIF =7173,
BMP =6677,
PNG =13780,
COM =7790,
EXE =7790,
DLL =7790,
RAR =8297,
ZIP =8075,
XML =6063,
HTML =6033,
ASPX =239187,
CS =117115,
JS =119105,
TXT =210187,
SQL =255254,
BAT =64101,
BTSEED =10056,
RDP =255254,
PSD =5666,
PDF =3780,
CHM =7384,
LOG =70105,
REG =8269,
HLP =6395,
DOC =208207,
XLS =208207,
DOCX =208207,
XLSX =208207,
}
頁:
[1]