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;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值