显示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;
}
}
{
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();
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();
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· 【全网最全教程】使用最强DeepSeekR1+联网的火山引擎,没有生成长度限制,DeepSeek本体