thedougster
Programmer
Within a C# program, is there any way to tell if a file is a text file or not? I mean a real way, not just basing your conclusion on a file name extension.
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
static bool IsTextFile(string fileName)
{
byte[] file;
using (System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
file = new byte[stream.Length];
stream.Read(file, 0, file.Length);
}
if (file.Length > 3 && ((file[0] == 0x00 && file[1] == 0x00 && file[2] == 0xFE && file[2] == 0xFF /*UCS-4*/)))
return true;
else if (file.Length > 2 && ((file[0] == 0xEF && file[1] == 0xBB && file[2] == 0xBF /*UTF-8*/)))
return true;
else if (file.Length > 1 && ((file[0] == 0xFF && file[1] == 0xFE /*Unicode*/)))
return true;
else if (file.Length > 1 && (file[0] == 0xFE && file[1] == 0xFF /*Unicode Big Endian*/))
return true;
else
{
for (int i = 0; i < file.Length; i++)
if (file[i] > 0x80)
return false;
return true;
}
}
file[2] == 0xFE && file[2] == 0xFF
file[3] == 0xFF
file = new byte[stream.Length];
stream.Read(file, 0, file.Length);