手记

显示Web site目录的图片

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

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

代码

 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 < allowExtension.Length; 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<FileInfo> lfi = new List<FileInfo>();

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

 

 

0人推荐
随时随地看视频
慕课网APP