ASP.Net中,如何自动保存文件到指定位置

  • Post author:
  • Post category:其他



代码示例如下:




//提供下载源地址(在服务器上的地址)




string srcPath = “C:\text.txt”;






FileInfo fileInfo = new FileInfo(srcPath);




//若该文件存在则弹出对话框让你选择保存地址(本地)




if (fileInfo.Exists)




{




Response.AddHeader(“Content-Disposition”, “attachment;filename=” + fileInfo.Name);




Response.WriteFile(srcPath);




Response.Flush();




Response.Close();




}






补充:不弹出对话框代码如下:




/**//**//** <summary>




/** 下载文件




/** </summary>




/** <param name=”filename”>文件物理地址</param>






protected void DownloadFile(string filename)




…{





string saveFileName = “test.xls”;




int intStart = filename.LastIndexOf(“\”)+1;




saveFileName = filename.Substring(intStart,filename.Length-intStart);




FileStream MyFileStream;




long FileSize;






MyFileStream = new FileStream(filename,FileMode.Open);




FileSize = MyFileStream.Length;






byte[] Buffer = new byte[(int)FileSize];




MyFileStream.Read(Buffer, 0, (int)FileSize);




MyFileStream.Close();






Response.AddHeader(“Content-Disposition”, “attachment;filename=”+saveFileName);




Response.ContentEncoding = System.Text.Encoding.GetEncoding(“GB2312”);




Response.ContentType = “application/vnd.ms-excel”;






Response.BinaryWrite(Buffer);




Response.Flush();




Response.Close();




Response.End();






}