实现这个功能,需要使用一个System.IO名称空间。只需判断文件流前两个字节即可。
参考代码:
View Code
string
GetFileCass(
string
path)
{
try
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass = string .Empty;
byte buffer;
byte [] b = new byte [ 2 ];
buffer = reader.ReadByte();
b[ 0 ] = buffer;
fileClass = buffer.ToString();
buffer = reader.ReadByte();
b[ 1 ] = buffer;
fileClass += buffer.ToString();
reader.Close();
fs.Close();
return fileClass;
}
catch
{
return string .Empty;
}
}
{
try
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass = string .Empty;
byte buffer;
byte [] b = new byte [ 2 ];
buffer = reader.ReadByte();
b[ 0 ] = buffer;
fileClass = buffer.ToString();
buffer = reader.ReadByte();
b[ 1 ] = buffer;
fileClass += buffer.ToString();
reader.Close();
fs.Close();
return fileClass;
}
catch
{
return string .Empty;
}
}
例子演示:
<
asp:FileUpload
ID
="FileUpload1"
runat
="server"
/><
br
/>
< asp:Button ID ="Button1" runat ="server" Text ="Get File Extension Info" onclick ="Button1_Click" />< br />
< p ></ p >
< asp:Label ID ="lblExtension" runat ="server" Text ="" ></ asp:Label >< br />
< asp:Label ID ="lblFileClass" runat ="server" Text ="" ></ asp:Label >
< asp:Button ID ="Button1" runat ="server" Text ="Get File Extension Info" onclick ="Button1_Click" />< br />
< p ></ p >
< asp:Label ID ="lblExtension" runat ="server" Text ="" ></ asp:Label >< br />
< asp:Label ID ="lblFileClass" runat ="server" Text ="" ></ asp:Label >
按钮事件:
View Code
protected
void
Button1_Click(
object
sender, EventArgs e)
{
if ( ! File.Exists( this .FileUpload1.PostedFile.FileName))
{
// follow Js class, download address: http://www.cnblogs.com/insus/articles/1341703.html
Insus.NET.InsusJsUtility objJs = new Insus.NET.InsusJsUtility();
objJs.JsAlert( " You did not specify a file. " );
return ;
}
string path = this .FileUpload1.PostedFile.FileName;
this .lblExtension.Text = " Extension: " + path.Substring(path.LastIndexOf( " . " ));
this .lblFileClass.Text = " FileClass: " + GetFileCass(path);
}
{
if ( ! File.Exists( this .FileUpload1.PostedFile.FileName))
{
// follow Js class, download address: http://www.cnblogs.com/insus/articles/1341703.html
Insus.NET.InsusJsUtility objJs = new Insus.NET.InsusJsUtility();
objJs.JsAlert( " You did not specify a file. " );
return ;
}
string path = this .FileUpload1.PostedFile.FileName;
this .lblExtension.Text = " Extension: " + path.Substring(path.LastIndexOf( " . " ));
this .lblFileClass.Text = " FileClass: " + GetFileCass(path);
}
选择一个Excel文件得到的结果: