对网页进行编码,以显示文件夹中所有文件的名称和链接
本文关键字:文件 链接 文件夹 网页 编码 显示文件 显示 | 更新日期: 2023-09-27 17:58:53
背景故事和目标:我正在编写一个脚本,通过ftp将文件(文档)从服务器a发送到web服务器B。然后在B上,我希望asp.net网页显示所有文件的名称(以某种方式直观地通知用户哪些文件在哪个文件夹中),并提供该文件的链接。
我的问题是:使用asp.net和C#的网站显示目录和子目录内容的好方法是什么?只需从上传的根目录中开始遍历文件结构就可以了吗?还是我应该修改脚本,在文件夹结构上生成并发送一个xml文件,然后使用XmlDataSource?如何设置XmlDataSource的数据路径以确保它将使用上载的xml文件?
注意:我认为两者都存在一些并发问题。但我认为这是一个单独的stackoverflow问题。
我认为最简单的方法是从上传文件的目录开始使用文件结构(而不是从根目录)。您可以在<AppSettings>
部分的web.config
文件中保存该目录的路径,然后使用File
和Directory
类读取其结构。
在web.config
中
<appSettings>
<add key="UploadDirectory" value="~/Upload/"/>
</appSettings>
在后面的代码中
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string DirectoryName = Request.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadDirectory"]);
if (Directory.Exists(DirectoryName))
{
String[] Files = Directory.GetFiles(DirectoryName);
myRepeater.DataSource = Files;
myRepeater.DataBind();
}
}
}
protected void myRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
LinkButton FileName = (LinkButton)e.Item.FindControl("FileName");
String fullName = (String)e.Item.DataItem;
FileName.Text = fullName.Substring(fullName.LastIndexOf("''") + 1);
FileName.CommandArgument=fullName.Substring(fullName.LastIndexOf("''") + 1);
}
}
protected void myRepeater_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName=="GOTO")
{
Response.Redirect(System.Configuration.ConfigurationManager.AppSettings["UploadDirectory"]+(String)e.CommandArgument);
}
}
在aspx 中
<asp:Repeater ID="myRepeater" OnItemDataBound="myRepeater_OnItemDataBound" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton runat="server" ID="FileName" CommandName="GOTO"></asp:LinkButton></li>
</ItemTemplate>
<FooterTemplate>
</ul></FooterTemplate>
</asp:Repeater>
使用此处的代码,您可以只允许登录用户查看文件夹内容。假设您将登录的用户存储在Session对象中,以下是转换为C#的代码,加上仅对登录用户的检查:
string dir = Request.Form("dir");
if (string.IsNullOrEmpty(dir))
dir = "/";
if (Session["Logged_User"] == null)
{
Response.Write("Not Authorized");
Response.End();
}
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Server.MapPath(dir));
StringBuilder sb = new StringBuilder();
sb.Append("<ul class='"jqueryFileTree'" style='"display: none;'">").Append(Environment.NewLine);
foreach (System.IO.DirectoryInfo di_child in di.GetDirectories())
{
sb.AppendFormat("'t<li class='"directory collapsed'"><a href='"#'" rel='"{0}'">{1}</a></li>'n", dir + di_child.Name, di_child.Name);
}
foreach (System.IO.FileInfo fi in di.GetFiles())
{
string ext = (fi.Extension.Length > 1) ? fi.Extension.Substring(1).ToLower() : "";
sb.AppendFormat("'t<li class='"file ext_{0}'"><a href='"#'" rel='"{1}'">{2}</a></li>'n", ext, dir + fi.Name, fi.Name);
}
sb.Append("</ul>");
Response.Write(sb.ToString());