判断非文本文件格式:
public static bool IsAllowedExtension(FileUpload hifile)
{
Stream fs = hifile.PostedFile.InputStream;
BinaryReader r = new BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
r.Close();
fs.Close();
if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar,208207是doc/xls
{
return true;
}
else
{
return false;
}
}
判断文件方式:
public static bool IsTextFile(FileUpload hifile)
{
//要比对的字节,越大,正确度越高,但32个只够了.
char[]buf = new char[32]; //实际读到的字符数
int readint = 0;
try
{
StreamReader reader = new StreamReader(hifile.PostedFile.InputStream);
//最多读 buf.Length 个字符
readint = reader.ReadBlock(buf, 0, buf.Length);
reader.Close(); //比对是否存在 '\0' 这个字符
for (int i = 0; i < readint; i++)
{
if (buf[i] == '\0')
{
return false; //存在:这个就不是文本文件
}
} //没找到,那么很大概率是文本文件
return true;
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
来源:http://www.cnblogs.com/94cool/archive/2009/06/22/1508513.html