1. 程式人生 > >C#對檔案操作小結

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;