ASP.NET中文件流的使用——下载Excle文件、文件的读取和写入

  /// 
  /// 下载文件
  /// 使用流输出
  /// 
  /// 
  /// 
  private void Button1_Click(object sender, System.EventArgs e)
  {
   string sFileName = Server.MapPath("./工作用常用电话号码.xls");
   FileStream fileStream=new FileStream(sFileName,FileMode.Open);
   long fileSize = fileStream.Length; 
   byte[] fileBuffer=new byte[fileSize]; 
   fileStream.Read(fileBuffer, 0, (int)fileSize); 
   //如果不写fileStream.Close()语句,用户在下载过程中选择取消,将不能再次下载
   fileStream.Close();

   Context.Response.ContentType="application/octet-stream"; 
   Context.Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(sFileName,Encoding.UTF8 ));
   Context.Response.AddHeader("Content-Length",fileSize.ToString()); 

   Context.Response.BinaryWrite(fileBuffer); 
   Context.Response.End(); 
   Context.Response.Close();
  }


  /// 
  /// 下载文件
  /// 直接输出文件方式
  /// 
  /// 
  /// 
  private void Button2_Click(object sender, System.EventArgs e)
  {
   string saveFileName = "工作用常用电话号码.xls";

   Response.Clear();
   Response.Buffer= true;
   //Response.Charset = "utf-8";//可有可无?

   //下面两个语句是一个含义,不知网上的人为什么要加一个this,非常的不解!
   //this.EnableViewState = false;
   EnableViewState = false;

   //Response.ContentType = "application/ms-excel"; //可有可无?
   //Response.ContentEncoding = System.Text.Encoding.UTF8;//可有可无?
   
   //直接写下面的语句,客户端看到的文件名是乱码
   //Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName); 
   //必须写成这种
   Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(saveFileName,Encoding.UTF8 ));

   Response.WriteFile(saveFileName); 
   Response.Flush();

   Response.End();//End和Close的顺序是什么,测试时,两个位置排列交换后对执行没有任何影响
   Response.Close();
  }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace 文件流
{
    class Program
    {
        static void Main(string[] args)
        {
            //C#文件流写文件,默认追加FileMode.Append
            string msg = "ok";
            byte[] myByte = System.Text.Encoding.UTF8.GetBytes(msg);
            using (FileStream fsWrite = new FileStream(@"C:\1.txt", FileMode.Append))
            {
                fsWrite.Write(myByte, 0, myByte.Length);
            };
 
            //c#文件流读文件
            using (FileStream fsRead = new FileStream(@"C:\1.txt", FileMode.Open))
            {
                int fsLen = (int)fsRead.Length;
                byte[] heByte = new byte[fsLen];
                int r = fsRead.Read(heByte, 0, heByte.Length);
                string myStr = System.Text.Encoding.UTF8.GetString(heByte);
                Console.WriteLine(myStr);
                Console.ReadKey();
            }
        }
    }
}


你可能感兴趣的:(C#,ASP.NET)