fileStream操作

iamzxf發表於2015-06-06


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileStreamForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FileStream fs;
            try
            {
                fs = File.Create(fname.Text);
            }
            catch
            {
                MessageBox.Show("建立檔案時出錯!", "錯誤", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                return;
            }

            byte[] content = new UTF8Encoding(true).GetBytes(this.richTextBox1.Text);
            try
            {
                fs.Write(content, 0, content.Length);
                fs.Flush();
                MessageBox.Show("儲存成功");
            }
            catch
            {
                MessageBox.Show("檔案寫入錯誤");
            }
            finally
            {
                fs.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = fname.Text;
            UTF8Encoding temp = new UTF8Encoding(true);
            FileStream fs;

            try
            {
                fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            }
            catch {
                MessageBox.Show("建議檔案出錯");
                return;
            }

            byte[] b = new byte[fs.Length];
            try
            {
                fs.Read(b, 0, (int)fs.Length);
                richTextBox1.Text = temp.GetString(b);
            }
            catch
            {
                MessageBox.Show("讀取檔案出錯");
            }
            finally
            {
                fs.Close();
            }
        }
    }
}



相關文章