C#對文件操作小結

private void button2_Click(object sender, EventArgs e)
        {
            //創建一個二進制文件
            BinaryWriter bw;           
            FileStream fs = new FileStream("D://mytest.data", FileMode.Create);
            bw = new BinaryWriter(fs);
            bw.Write("我的測試文章,123 ,welcome to you!");//寫入
            fs.Close();
            bw.Close();//關閉

            ////讀一個二進制文件
            BinaryReader br;
            string str = "";
            FileStream fs2 = new FileStream("D://mytest.data", FileMode.Open);
            br = new BinaryReader(fs2);
            byte[] DocByte = br.ReadBytes((int)fs2.Length);

            str = Encoding.UTF8.GetString(DocByte);
            fs2.Close();
            br.Close();

            this.textBox1.Text = str;


        }

 private void button1_Click(object sender, EventArgs e)
        {
            //文本文件操作:創建/讀取/拷貝/刪除
            string filepath = "D://myfile.txt";
            StreamWriter sw = File.CreateText(filepath);
            sw.Write("use write to write it");
            sw.WriteLine("use sw writeline");
            sw.Close();

            StreamReader sr = File.OpenText(filepath);
            string str = sr.ReadLine();
            this.textBox1.Text = str;
            sr.Close();
            //文件的刪除。
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }

  //流文件操作
            FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            //Byte[] info = new UTF8Encoding(true).GetBytes("This is my test file,也可用中文顯示");  //轉爲bytes       
            //fs.Write(info, 0, info.Length);

            //或者用StreamWriter
            StreamWriter sw = new StreamWriter(fs);
            sw.Write("This is my test file,也可用中文顯示");
            sw.Close();
            fs.Close();


          

            FileStream fs2 = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            byte[] cByte = new byte[1024];
            fs2.Read(cByte, 0, cByte.Length);
            string content = Encoding.UTF8.GetString(cByte);
            this.textBox1.Text = content;
            //或者用StreamReader來實現
            StreamReader sr = new StreamReader(fs2);
            //this.textBox1.Text = sr.ReadToEnd();

            fs2.Close();
            sr.Close();

}

附: //轉換類型
            System.Text.Encoding encode = System.Text.Encoding.Default;
            byte[] bytes = encode.GetBytes("這是我的測試中文體");
            string strout = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);
            this.textBox1.Text = strout;

發佈了57 篇原創文章 · 獲贊 6 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章