C#中对文件的读写

FileStream-------表示可以被写或被读,或二者都可的文件,此文件可以同步或异步读和写
StreamReader------从流中读取字符数据,并可通过使用 FileStream被创建为基类。
StreamWriter------向流写字符数据,可通过使用FileStream被创建为基类。

1. 利用StreamWriter,StreamReader实现对文件的读写:
            StreamWriter sw = new StreamWriter("D:\\firsttext.txt", true);
            sw.WriteLine("you ran the StreamWriteDemo program on:");
            sw.WriteLine(DateTime.Now);
            sw.Close();

            StreamReader sr = new StreamReader("D:\\firsttext.txt");
            string strline = null;
            while ((strline = sr.ReadLine()) != null)
            {
                Console.WriteLine(strline);
            }


2. 利用FileStream构造StreamWriter和StreamReader来读写文件
                FileStream fs = new FileStream("D:\\firsttext.txt", FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("Are you Fightting now?");
                sw.Close();

                 FileStream fsread = new FileStream("D:\\firsttext.txt", FileMode.OpenOrCreate, FileAccess.Read);
                StreamReader sr = new StreamReader(fsread);
                while ((strline = sr.ReadLine()) != null)
                {
                    Console.WriteLine(strline);
                }

3. 利用FileStream读写文件
            FileStream fwrite = new FileStream("D:\\stream.txt", FileMode.Append, FileAccess.Write);
            string str = Console.ReadLine();
            byte[] bt = new byte[1000];
            bt = Encoding.ASCII.GetBytes("\n" + str);
            fwrite.Write(bt, 0, str.Length);
            fwrite.Close();

            FileStream fread = new FileStream("D:\\stream.txt", FileMode.OpenOrCreate, FileAccess.Read);
            byte[] btread = new byte[1000];
            fread.Read(btread, 0, 1000);
            string s = Encoding.ASCII.GetString(btread);
            fread.Close();

posted @ 2010-08-25 13:47  启明星工作室  阅读(565)  评论(0编辑  收藏  举报