protected void Button2_Click(object sender, EventArgs e)
{
bool ok = true;
string fileName;
fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc";
try
{
Response.ClearHeaders();
Response.ContentType = "application/msword;";
Response.Charset = "UTF-8";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=/"{0}/"", fileName));
Response.BinaryWrite(Encoding.Default.GetBytes(strr));
}
catch (Exception ex)
{
ok = false;
Response.Write("生成文件失败:" + ex.Message + ",请稍后再试。");
CreateGbpt(fileName, strr);
}
if (ok)
{
Response.End();
}
}
private void CreateFile(string fileName, string text)
{
bool ok = true;
string filePath;
filePath = Server.MapPath(fileName);
Encoding code = Encoding.GetEncoding("utf-8"); //定义编码
try
{
using (StreamWriter sw = new StreamWriter(filePath, false, code))
{
sw.Write(text.Trim());
sw.Flush();
}
}
catch (DirectoryNotFoundException ex)
{
ok = false;
Response.Write("写入文件出错:" + ex.Message);
}
//文件写入成功,下载文件
if (ok)
{
DownLoadFile(fileName);
}
}
private void DownLoadFile(string fileName)
{
bool ok = true;
if (System.IO.File.Exists(Server.MapPath(fileName)))
{
try
{
Response.ClearHeaders();
Response.ContentType = "application/msword;";
Response.Charset = "UTF-8";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=/"{0}/"", fileName));
Response.BinaryWrite(GetFileBytes(fileName));
}
catch (Exception ex)
{
ok = false;
Response.Write("文件不能提供下载,请手动点击下载。" + ex.Message);
}
if (ok)
{
File.Delete(Server.MapPath(fileName));
Response.End();
}
else
{
//HypFile.NavigateUrl = fileName;
//HypFile.Text = "生成文件:" + fileName + ",请点击下载";
}
}
}
private byte[] GetFileBytes(string fileName)
{
try
{
using (System.IO.FileStream fileStream = new System.IO.FileStream (System.Web.HttpContext.Current.Server.MapPath(fileName), System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
return bytes;
}
}
catch
{
return null;
}
}