• 取得文件真正扩展名类型


    实现这个功能,需要使用一个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文件得到的结果:

  • 相关阅读:
    fopen C++
    Jungle Roads(最小生成树+并查集)
    Magic Number(dp)
    error: macro names must be identifiers
    <errors>'MessageBoxA' : function does not take 1 parameter
    归并排序模板
    MFC程序出现“Debug Assertion Failed! File:afx.inl Line:177”错误
    构造函数初始化列表
    (Codeforces Round #136 (Div. 2))A. Little Elephant and Function(递归分析,简单)
    Argus(ZOJ Problem Set 2212)(优先队列)
  • 原文地址:https://www.cnblogs.com/insus/p/1980495.html
Copyright © 2020-2023  润新知