How can I test whether a file that I\'m opening in C# using FileStream is a \"text type\" file? I would like my program to open any file that is text based, for example, .t
I have a below solution which works for me.This is general solution which check all types of Binary file.
///
/// This method checks whether selected file is Binary file or not.
///
public bool CheckForBinary()
{
Stream objStream = new FileStream("your file path", FileMode.Open, FileAccess.Read);
bool bFlag = true;
// Iterate through stream & check ASCII value of each byte.
for (int nPosition = 0; nPosition < objStream.Length; nPosition++)
{
int a = objStream.ReadByte();
if (!(a >= 0 && a <= 127))
{
break; // Binary File
}
else if (objStream.Position == (objStream.Length))
{
bFlag = false; // Text File
}
}
objStream.Dispose();
return bFlag;
}