为了账号安全,请及时绑定邮箱和手机立即绑定

取得文件真正扩展名类型

标签:
算法

实现这个功能,需要使用一个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;
        }
    }

 

例子演示:

<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>

 

按钮事件:

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);
    }

 

选择一个Excel文件得到的结果:

 

 

 

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消