如何使用c#将服务器文件下载到客户端系统

时间:2014-11-05 04:39:22

标签: c# asp.net

string filePath1 = (sender as LinkButton).CommandArgument;
string filepath = ("D:\\RetailAgreement\\" + filePath1);
FileInfo myfile = new FileInfo(filepath);
if (filePath1 != "")
{
    Response.ClearContent();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
    Response.AddHeader("Content-Length", myfile.Length.ToString());
    Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
    Response.TransmitFile(myfile.FullName);
    Response.End();

}

我试过这样但不行, 我不知道我哪里出错了。我正在使用C#3.0

2 个答案:

答案 0 :(得分:0)

使用此代码。

string path = Server.MapPath("~/DownloadedExcelFilesOp4/myfile.xlsx");
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            string Outgoingfile = "myfile.xlsx";
            if (file.Exists)
            {
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.WriteFile(file.FullName);
                Response.Flush();
                Response.Close();

            }
            else
            {
                Response.Write("This file does not exist.");
            }

答案 1 :(得分:0)

File.Copy("D:\\RetailAgreement\\",Server.Mapth("YourAplicationPath\\MyFiles"), true);
//Copy Files to Your Application Path
string path = Server.MapPath("~\MyFiles" + filePath1");
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            string Outgoingfile = "myfile.xlsx";
            if (file.Exists)
            {
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.WriteFile(file.FullName);
                Response.Flush();
                Response.Close();

            }
            else
            {
                Response.Write("This file does not exist.");
            }