C#使用FileStream复制一个任意文件
作者:CGGUANG 时间:2022-04-17 19:55:17
FileStream,顾名思义,文件流。流,是字节流。我的理解是,硬盘上存在一个字节流,内存里也有一个字节流,它们是对应的。程序运行时,我们只能对内存里的字节流直接操作,在它被关闭的时候,它的内容自动写入硬盘上的相应字节流。
复制一个文件的基本思路是:逐一读取原文件流的字节,逐一写入新文件流中。分别用到文件流的ReadByte()和WriteByte()方法。这里要注意的是,读取时以字节为单位,一个字节如下图所示
是一个0和1组合的序列。ReadByte()读取一个字节后将这个序列求值,返回的是整形数值。如果读到文件的尽头了,不能成功读取字节了,返回的是-1。这个设计是非常合理的。因为只要是个字节,总是能求出它大于或等于0的值的。没有字节了,就返回-1了。这样的话,可以把-1作为循环读取终止的标志。
我下面以一个图片文件的复制为例讲解。
在C盘新建一个画图文件,另存为png格式,文件名pic1。
然后执行以下代码:
using System;
using System.IO;
namespace Demo
{
class Program {
public static void Main(string[] args)
{
FileStream fs1 = new FileStream("c:/pic1.png",FileMode.Open);//FileAccess is dispensable.
//FileAccess is the extra contract.
FileStream fs2 = new FileStream("c:/pic2.png",FileMode.Create);
int d;
byte b;
while( ( d = fs1.ReadByte() ) != -1 )
{
b = (byte)d;
fs2.WriteByte( b );
}
fs1.Close();
fs2.Close();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
会在c盘下生成一个和pic1一模一样的图片文件pic2.
来源:https://blog.csdn.net/CGGUANG/article/details/53299557
标签:C#,FileStream,复制文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springboot解决java.lang.ArrayStoreException异常
2023-06-24 19:22:25
![](https://img.aspxhome.com/file/2023/0/76250_0s.jpg)
详解Maven profile配置管理及激活profile的几种方式
2022-07-01 08:54:46
java的Arrays工具类实战
2023-08-21 15:46:36
![](https://img.aspxhome.com/file/2023/6/58076_0s.png)
浅谈JAVA中输入输出流实例详解
2022-10-21 05:20:57
![](https://img.aspxhome.com/file/2023/1/81881_0s.png)
详解Android系统中的root权限获得原理
2023-06-19 20:28:25
![](https://img.aspxhome.com/file/2023/9/76279_0s.jpg)
Java 集合框架之List 的使用(附小游戏练习)
2023-11-24 10:33:40
![](https://img.aspxhome.com/file/2023/7/59947_0s.png)
JAVA熔断和降级真实关系的图文详解
2023-11-30 12:39:20
![](https://img.aspxhome.com/file/2023/7/67957_0s.png)
Java模拟qq软件的详细过程
2022-01-27 15:06:19
![](https://img.aspxhome.com/file/2023/9/73069_0s.png)
JPA Specification常用查询+排序实例
2023-11-23 04:56:32
![](https://img.aspxhome.com/file/2023/3/59423_0s.png)
java泛型中占位符T和?有什么区别
2022-07-05 02:53:56
![](https://img.aspxhome.com/file/2023/6/64746_0s.png)
基于WPF实现简单的文件夹比较工具
2023-11-15 16:08:34
![](https://img.aspxhome.com/file/2023/6/74836_0s.png)
springboot+rabbitmq实现智能家居实例详解
2022-09-05 12:23:39
![](https://img.aspxhome.com/file/2023/0/76480_0s.jpg)
Idea2020.2创建JavaWeb项目(部署Tomcat)方法详解
2023-11-02 13:29:52
![](https://img.aspxhome.com/file/2023/4/58904_0s.png)
Spring+SpringMVC+MyBatis深入学习及搭建(三)之MyBatis全局配置文件解析
2022-03-21 05:25:23
![](https://img.aspxhome.com/file/2023/2/84692_0s.png)
SpringBoot部署在tomcat容器中运行的部署方法
2023-08-04 13:02:28
JAVA回顾:封装,继承,多态
2021-09-26 20:17:59
![](https://img.aspxhome.com/file/2023/7/67627_0s.png)
详解Docker学习笔记之搭建一个JAVA Tomcat运行环境
2022-09-03 02:26:06
SpringMVC学习之JSTL条件行为和遍历行为详解
2021-08-19 08:56:09
为何Java8需要引入新的日期与时间库
2023-12-16 06:02:23
![](https://img.aspxhome.com/file/2023/9/71659_0s.png)
使用Java实现qq邮箱发送邮件
2023-10-14 18:24:36
![](https://img.aspxhome.com/file/2023/1/58561_0s.jpg)