C#中的各種流

來源:互聯網
上載者:User

       //Stream是一個抽象類別,不能直接執行個體化
        //FileStream繼承於Stream ,讀寫檔案流       
        //StreamWriter繼承於TextWriter(抽象類別,繼承於MarshalByRefObject, IDisposable),可以操作Stream
        //StreamReader繼承於TextReader(抽象類別,繼承於MarshalByRefObject, IDisposable),可以操作Stream
        //MemoryStream繼承於Stream
        //BufferedStream繼承於Stream       

      StreamWriter和StreamReader可以直接操作檔案進行讀寫,但前提是檔案是已經存在的,如果沒有檔案存在,會拋出異常。

        //檔案流操作
        private void btnFileStream_Click(object sender, EventArgs e)
        {
            string path=@"c:\test.txt";

            #region FileStream 讀寫檔案必須以位元組形式
            //向檔案中寫入流
            using (FileStream fs = File.Create(path))
            {               
                //byte[] info = new UTF8Encoding(true).GetBytes("this is some text");
                Byte[] info = Encoding.GetEncoding("UTF-8").GetBytes("this is some text");
                fs.Write(info, 0, info.Length);
            }

            //開啟檔案讀迴流
            using (FileStream fs = File.OpenRead(path))
            {
                string result = string.Empty;
                byte[] info = new byte[1024];
                //UTF8Encoding temp = new UTF8Encoding(true);
                while (fs.Read(info, 0, info.Length) > 0)
                {
                    //result += temp.GetString(info);
                    result += Encoding.GetEncoding("UTF-8").GetString(info);
                }
                System.Diagnostics.Debug.WriteLine(result);
            }

            #endregion

            #region StreamWriter 以字元的形式寫入 1.可以往Stream裡寫,2.也可以直接往路徑檔案裡寫資訊(前提是檔案已存在)

            //開啟檔案,在檔案末尾附加資訊
            FileStream fileStream = new FileStream(path,FileMode.Append);
            StreamWriter sw = new StreamWriter(fileStream);
            sw.WriteLine("This is the appended line.");
            sw.Close();
            fileStream.Close();

            //開啟檔案,在檔案末尾附加資訊
            using (FileStream file = new FileStream(path, FileMode.Append))
            {
                using (StreamWriter writer = new StreamWriter(file))
                //using (StreamWriter writer = new StreamWriter(path))
                {
                    writer.WriteLine("this a the second appended line.");
                    writer.Write("this a the third appended line.");
                }
            }

             //如果檔案已經存在,可以及直接用StreamWriter寫入,不用File

             //using (StreamWriter writer = new StreamWriter(path))
             // {
                   // writer.WriteLine("this a the second appended line.");
                   // writer.Write("this a the third appended line.");
              // }

            #endregion

            #region StreamReader 1.可以從Stream裡讀,2.也可以直接從檔案裡讀資訊

            //讀取檔案常值內容 1
            using (StreamReader reader = new StreamReader(path,Encoding.UTF8))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    System.Diagnostics.Debug.WriteLine(line);
                }
            }

            //讀取檔案常值內容 2
            using(FileStream fs1=File.OpenRead(path))
            {
                using (StreamReader reader = new StreamReader(fs1,Encoding.GetEncoding("GB2312")))
                {
                    string result = reader.ReadToEnd();
                    System.Diagnostics.Debug.WriteLine(result);
                }
            }

            #endregion

            #region 記憶體流,可讀可寫,操作單位是位元組,主要作用是在記憶體中操作位元組流,最後可寫入到Stream中
           
            using (MemoryStream ms = new MemoryStream())
            {
                UnicodeEncoding uniEncoding = new UnicodeEncoding();
                byte[] info = uniEncoding.GetBytes(" this is MemoryStream");
               
                //把資訊寫入到MemoryStream中
                ms.Write(info, 0, info.Length);

                byte[] result=new byte[ms.Length];
                //從流中讀取資訊到位元組數組中
                ms.Read(result, 0, info.Length);

                using (Stream s = new FileStream("c:/aa.txt",FileMode.Create))
                {
                    //可以將記憶體流寫入到Stream中:this is MemoryStream
                    ms.WriteTo(s);                   
                }
            }
            #endregion

            //緩衝區是記憶體中的位元組塊,用於快取資料,從而減少對作業系統的調用次數。 緩衝區可提高讀取和寫入效能。
            //BufferedStream
        }

 

寫日誌:

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "log files(*.log)|*.log|txt files(*.txt)|*.txt|All files(*.*)|*.*";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
            FileStream fs = null;
            StreamWriter sw = null;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    fs = (FileStream)saveFileDialog.OpenFile();
                    sw = new StreamWriter(fs);
                    sw.Write(txtImportLog.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("日誌匯出失敗!" + ex.Message);
                }
                finally
                {
                    sw.Flush();
                    sw.Close();
                    fs.Close();
                }
            }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.