读写文件Filestream

//文件目录
            string path = @"C:\Users\Administrator\Documents\Test\a.txt";
            string path2 = @"F:\b.txt";
            //如果文件2不存在,创建文件2
            if (!File.Exists(path2))
            {
                FileStream stream = File.Create(path2);
                //完毕要后关闭流,否则后面会出错,因为流被这一步占用,后面无法使用
                stream.Close();
            }
            //如果文件存在,就读取,否则跑出异常
            if (File.Exists(path))
            {
                //建立读取和写入流
                FileStream reader = File.OpenRead(path);
                FileStream writer = File.OpenWrite(path2);
                //每次读取的最大字节
                int maxByte = 100;
                while(true)
                {
                    //存储每次读取的字节数组
                    byte[] bytes = new byte[maxByte];
                    //返回每次读取到的字节数,前面的都是最大字节数,当最后一次时,剩余多少
                    //个字节,就会读取多少个字节,当到达文件末尾时,返回0
                    int byteCount = reader.Read(bytes, 0, maxByte);
                    //写入字节,注意不是写入最大读取字节数,而是每次读取到的字节数
                    writer.Write(bytes, 0, byteCount);
                    //如果读取到文件末尾,结束
                    if (byteCount == 0)
                    {
                        break;
                    }
                }
                //关闭读写流
                reader.Close();
                writer.Close();
            }
            else
            {
                throw new Exception("文件不存在");
            }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值