Asp.net获取服务器指定文件夹目录文件并提供下载的方法
本文实例讲述了asp.net获取服务器指定文件夹目录文件并提供下载的方法。分享给大家供大家参考。具体实现方法如下:
if (directory.exists(dirpath))
{
//获得目录信息
directoryinfo dir = new directoryinfo(dirpath);
//获得目录文件列表
fileinfo[] files = dir.getfiles("*.*");
string[] filenames = new string[files.length];
//临时数据表
datatable dt = new datatable();
dt.columns.add("filename");
foreach (fileinfo fileinfo in files)
{
datarow dr = dt.newrow();
dr["filename"] = fileinfo.name;
dt.rows.add(dr);
}
repeater1.datasource = dt;
repeater1.databind();
}
if (e.commandname == "down")
{
try
{
string downloadfilename = "~/uploads/" + e.commandargument.tostring();//文件路径
string filepath = server.mappath(downloadfilename);
string filename = path.getfilename(filepath);
fileinfo file = new fileinfo(filepath);
response.clear();
response.contenttype = "application/octet-stream";
response.addheader("content-disposition", "attachment; filename=" + httputility.urlencode(filename, system.text.encoding.utf8));
response.addheader("content-length", file.length.tostring());
response.flush();
response.writefile(filepath);
}
catch
{
response.write("<script>alert('没有找到下载的源文件')</script>");
}
}
希望本文所述对大家的asp.net程序设计有所帮助。