ITPub博客

首页 > IT职业 > IT生活 > 显示Web site目录的图片

显示Web site目录的图片

IT生活 作者:flow_water 时间:2021-09-09 09:46:37 0 删除 编辑

需要显示目录的图片,有一点需要注意的,就是目录中的文件不一定全是图片文件,如果显示,显示时也许会有问题,另外还需要判断目录是否存在,因为用户有可能把目录删除,这样在显示时会出现异常。

下面代码是判断文件是否为图片文件,如果以文件后缀来判断,有可能取到不是真正的图片文件。

代码

 private bool IsPicture(string filePath, string[] allowExtension)
    {
        try
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(fs);
            string fileClass;
            byte buffer;
            bool result = false;

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

            for (int i = 0; i             {
                if (string.Compare(fileClass, allowExtension[i], true) != 0) continue;
                result = true;
            }

            return result;
        }
        catch
        {
            return false;
        }
    }

  

下面是显示某一目录图片到DataList控件显示。

代码

 string filePath = "~/GalleryLibrary/Malaysia/槟城/";

        if (!Directory.Exists(Server.MapPath(filePath))) return;
        
        DirectoryInfo galleryFile = new DirectoryInfo(Server.MapPath(filePath));

        List lfi = new List();

        //255216是jpg;7173是gif;6677是BMP,13780是PNG;
        string[] fileExtension = { "255216", "7173", "6677", "13780" };

        foreach (FileInfo file in galleryFile.GetFiles())
        {
            if (IsPicture(Server.MapPath(filePath + file), fileExtension))
            {
                lfi.Add(file);
            }
        }

        this.DataList1.DataSource = lfi;
        this.DataList1.DataBind();

 

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1052/viewspace-2812111/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    74
  • 访问量
    618