欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.net获取服务器指定文件夹目录文件并提供下载的方法

程序员文章站 2024-02-21 21:27:16
本文实例讲述了asp.net获取服务器指定文件夹目录文件并提供下载的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:string dirpath =...

本文实例讲述了asp.net获取服务器指定文件夹目录文件并提供下载的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:
string dirpath = httpcontext.current.server.mappath("uploads/");
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程序设计有所帮助。