日期:2014-05-20  浏览次数:20748 次

C#保存文件
如下:
比如说我本地F盘有个文件test.txt 文件, 那么我想点击按钮 首先判断这个文件是否存在,如果不存在就弹出框,提示该文件已经不存在,如果存在就弹出框,提示下载, 就像csdn里下载一样,如图


------解决方案--------------------
下载方法执行
C# code
public   void   Save() 
{ 
if   (System.IO.File.Exists(fileName)) 
{ 
FileInfo   DownloadFile   =   new   FileInfo(fileName);   
System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.ClearHeaders(); System.Web.HttpContext.Current.Response.Buffer=false; 
System.Web.HttpContext.Current.Response.Charset   =   "GB2312 "; System.Web.HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.UTF8; 
System.Web.HttpContext.Current.Response.ContentType= "application/octet-stream "; 
System.Web.HttpContext.Current.Response.AppendHeader( "Content-Disposition ", "attachment;filename= "   +System.Web.HttpUtility.UrlEncode(DownloadFile.FullName,System.Text.Encoding.UTF8)); 
System.Web.HttpContext.Current.Response.AppendHeader( "Content-Length ",DownloadFile.Length.ToString()); 
// System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName); 
// System.Web.HttpContext.Current.Response.Flush(); 
// System.Web.HttpContext.Current.Response.End();//原来的程序 
byte[]   tmpbyte=new   byte[1024*8]; 
System.IO.FileStream   fs=DownloadFile.OpenRead(); 
int   count; 
while((count=fs.Read(tmpbyte,0,tmpbyte.Length))> 0) 
{ 
System.Web.HttpContext.Current.Response.BinaryWrite(tmpbyte); System.Web.HttpContext.Current.Response.Flush(); 
} 
fs.Close(); 
System.Web.HttpContext.Current.Response.End(); 
} 
}

------解决方案--------------------
xxx = Server.MapPath("~/xxx.txt");
if(File.Exists(xxx))
{
Response.Clear();
Response.ContentType= "application/octet-stream"; 
Response.AppendHeader("Content-Disposition", "attachment;filename="+ Path.GetFileName(xxx));
Response.WriteFile(xxx);
Response.End();
}
else
{
 Response.Write("文件不存在");
}

另外,文件必须放在网站目录下,而不是放在网站目录外面
------解决方案--------------------
C# code
protected void Page_Load(object sender, EventArgs e)
    {
        FileDown("D:/MyPassWord.pmb");
    }
    private void FileDown(string strPath)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(strPath);
        if (file.Exists)
        {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.FullName, System.Text.Encoding.UTF8));
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.Filter.Close();
            Response.WriteFile(file.FullName);
            Response.End();
        }
        else
        {
            ClientScript.RegisterStartupScript(GetType(), "", "<script language='javascript'>alert('文件不存在!');</script>");
        }
    }