OpenRead方法打開文件並讀取


實現效果:

  

知識運用
  File類的OpenRead方法    //實現打開現有文件以進行讀取

  public static FileStream OpenRead(string path)

  FileStream類的Read方法  //實現從流中讀取字節塊並將該數據寫入給定的緩沖區

  public overrider int Read (byte[] array, int offset, int count)

  補充:Encoding類的GetStrin方法  //實現將字節數組解碼為對應的字符串

實現代碼:

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog OFDialog = new OpenFileDialog();
                OFDialog.Filter = "文本文件(*.txt)|*.txt";
                OFDialog.ShowDialog();
                textBox1.Text = OFDialog.FileName;
                FileStream fs = File.OpenRead(textBox1.Text);
                byte[] bt=new byte[1024];
                while(fs.Read(bt,0,bt.Length)>0)
                {
                    textBox2.Text = Encoding.UTF8.GetString(bt);
                }
            }
            catch (Exception)
            { MessageBox.Show("請選擇文件"); }
        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM