C# 用FileStream实现文件拷贝

流程:

  1. 先创建第一个文件(picture1)的文件流
  2. 判断第二个文件是否存在,存在则删除。创建picture2和文件流
  3. 创建bytes缓冲区
  4. 利用do while循环先读后写
static void Main(string[] args)
        {
            string path = "picture1.jpg";
            FileStream fs1 = new FileStream(path, FileMode.Open, FileAccess.Read);
            if(File.Exists("picture2.jpg"))
            {
                File.Delete("picture2.jpg");
            }
            FileStream fs2 = new FileStream("picture2.jpg", FileMode.Create, FileAccess.Write);
            byte[] bytes = new byte[1024];
            int num;
            do
            {
                num = fs1.Read(bytes, 0, bytes.Length);
                fs2.Write(bytes, 0, bytes.Length);
            } while (num>0);
            fs2.Close();
            fs1.Close();
        }

结果:

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C#中的FileStream类来实现文件的复制操作。具体步骤如下: 1. 创建一个源文件FileStream对象,用于读取源文件的内容。 2. 创建一个目标文件FileStream对象,用于将源文件的内容写入目标文件。 3. 通过源文件FileStream对象读取源文件的内容,并通过目标文件FileStream对象将读取到的内容写入目标文件中。 4. 关闭源文件和目标文件FileStream对象。 下面是一个示例代码,演示如何使用FileStream实现文件的复制操作: ```csharp using System.IO; class Program { static void Main(string[] args) { // 源文件路径 string sourceFilePath = @"C:\source.txt"; // 目标文件路径 string targetFilePath = @"C:\target.txt"; // 创建源文件FileStream对象 using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read)) { // 创建目标文件FileStream对象 using (FileStream targetStream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write)) { // 读取源文件的内容,并将内容写入目标文件中 byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { targetStream.Write(buffer, 0, bytesRead); } } } } } ``` 在上面的代码中,我们首先创建了一个源文件FileStream对象和一个目标文件FileStream对象,然后通过源文件FileStream对象读取源文件的内容,并通过目标文件FileStream对象将读取到的内容写入目标文件中。最后,我们关闭了源文件和目标文件FileStream对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值