FileStream的使用
FileStream的使用
一.基本介绍:
二.FileStream读写文件实例:
string path1 = @"d\test\test1.txt";string path2= @"d\test\test2.txt";byte[] buffered = new byte[1024];using (FileStream fsr = new FileStream(path1, FileMode.Open, FileAccess.Read)) {using (FileStream fsw = new FileStream(path1, FileMode.OpenOrCreate, FileAccess.Write)) {int count = fsr.Read(buffered, 0, buffered.Length);while (true) {if (count == 0) break;fsw.Write(buffered, 0, buffered.Length);}}}
三.FileStream异步复制文件:
第一种方式: 不建议,复杂
private static FileStream inputS = null;private static FileStream OutputS = null;private static int bufferSize = 1024;private static byte[] buffered = new byte[1024];static void Main(string[] args){string path = @"d:\test1\test.txt";Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}");ReadAsync01(path);}public static void ReadAsync01(string path) {Console.WriteLine($"异步读取:{Thread.CurrentThread.ManagedThreadId}");inputS = new FileStream(path, FileMode.Open, FileAccess.Read,FileShare.Read,buffered.Length,true);inputS.BeginRead(buffered, 0, buffered.Length, OnCompleteRead, null);}//异步回调的方法private static void OnCompleteRead(IAsyncResult asyncResult) {Console.WriteLine($"异步回调{Thread.CurrentThread.ManagedThreadId}");//读取的字节数据int count =inputS.EndRead(asyncResult);string writePath = @"d:\test2\test2.txt";if (count > 0) {if (count < bufferSize){WriteAsync01(writePath, count);inputS.Close();}elseinputS.BeginRead(buffered, 0, buffered.Length, OnCompleteRead, null);}}public static void WriteAsync01(string path,int len){Console.WriteLine($"异步写入:{Thread.CurrentThread.ManagedThreadId}");byte[] buffered = new byte[1024];OutputS = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None, buffered.Length, true);OutputS.BeginWrite(buffered, 0, buffered.Length, OnCompleteRead, null);OutputS.Close();}//异步回调的方法private static void OnCompleteQWrite(IAsyncResult asyncResult){Console.WriteLine($"异步回调{Thread.CurrentThread.ManagedThreadId}");inputS.EndWrite(asyncResult);}}
第二种方式:
private string pathr = @"d:\test1\test1.txt"; private string pathw = @"d:\test2\test2.txt"; private int bufferSize= 1024; public async void read() {Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}");await ReadFileAsync();Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}");}public async Task ReadFileAsync() {Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}");byte[] buffered = new byte[bufferSize];using (FileStream fis = new FileStream(pathr, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, true)) {using (FileStream fws = new FileStream(pathw, FileMode.Open, FileAccess.Write, FileShare.None, bufferSize, true)) {int count = 0;count= await fis.ReadAsync(buffered, 0, buffered.Length);while (count != 0) {await fws.WriteAsync(buffered, 0, count);count = await fis.ReadAsync(buffered, 0, buffered.Length);}}}}
四.MemoryStream的使用:
①.基本介绍:
②主要的构造函数:
//// 摘要:// 使用初始化为零的可扩展容量初始化 System.IO.MemoryStream 类的新实例。public MemoryStream();//// 摘要:// 使用按指定要求初始化的可扩展容量初始化 System.IO.MemoryStream 类的新实例。//// 参数:// capacity:// 内部数组的初始大小(以字节为单位)。//// 异常:// T:System.ArgumentOutOfRangeException:// capacity 为负数。public MemoryStream(int capacity);//// 摘要:// 基于指定的字节数组初始化 System.IO.MemoryStream 类的无法调整大小的新实例。//// 参数:// buffer:// 从中创建当前流的无符号字节数组。//// 异常:// T:System.ArgumentNullException:// buffer 为 null。public MemoryStream(byte[] buffer);//// 摘要:// 在 System.IO.MemoryStream.CanWrite 属性按指定设置的状态下,基于指定的字节数组初始化 System.IO.MemoryStream// 类的无法调整大小的新实例。//// 参数:// buffer:// 从中创建此流的无符号字节的数组。//// writable:// System.IO.MemoryStream.CanWrite 属性的设置,确定该流是否支持写入。//// 异常:// T:System.ArgumentNullException:// buffer 为 null。public MemoryStream(byte[] buffer, bool writable);//// 摘要:// 基于字节数组的指定区域(索引)初始化 System.IO.MemoryStream 类的无法调整大小的新实例。//// 参数:// buffer:// 从中创建此流的无符号字节的数组。//// index:// buffer 内的索引,流从此处开始。//// count:// 流的长度(以字节为单位)。//// 异常:// T:System.ArgumentNullException:// buffer 为 null。//// T:System.ArgumentOutOfRangeException:// index 或 count 也不可小于零。//// T:System.ArgumentException:// 缓冲区长度减去 index 小于 count。public MemoryStream(byte[] buffer, int index, int count);//// 摘要:// 在 System.IO.MemoryStream.CanWrite 属性按指定设置的状态下,基于字节数组的指定区域,初始化 System.IO.MemoryStream// 类的无法调整大小的新实例。//// 参数:// buffer:// 从中创建此流的无符号字节的数组。//// index:// buffer 内的索引,流从此处开始。//// count:// 流的长度(以字节为单位)。//// writable:// System.IO.MemoryStream.CanWrite 属性的设置,确定该流是否支持写入。//// 异常:// T:System.ArgumentNullException:// buffer 为 null。//// T:System.ArgumentOutOfRangeException:// index 或 count 为负。//// T:System.ArgumentException:// 缓冲区长度减去 index 小于 count。public MemoryStream(byte[] buffer, int index, int count, bool writable);//// 摘要:// 在 System.IO.MemoryStream.CanWrite 属性和调用 System.IO.MemoryStream.GetBuffer 的能力按指定设置的状态下,基于字节数组的指定区域初始化// System.IO.MemoryStream 类的新实例。//// 参数:// buffer:// 从中创建此流的无符号字节的数组。//// index:// buffer 内的索引,流从此处开始。//// count:// 流的长度(以字节为单位)。//// writable:// System.IO.MemoryStream.CanWrite 属性的设置,确定该流是否支持写入。//// publiclyVisible:// 设置为 true 可以启用 System.IO.MemoryStream.GetBuffer,它返回无符号字节数组,流从该数组创建;否则为 false。//// 异常:// T:System.ArgumentNullException:// buffer 为 null。//// T:System.ArgumentOutOfRangeException:// index 或 count 为负数。//// T:System.ArgumentException:// 缓冲区长度减去 index 小于 count。public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible);
③.基本使用
public void MemoryStreamEx() {MemoryStream memoryStream0 = new MemoryStream();MemoryStream memoryStream1 = new MemoryStream(1024);byte[] buffered = new byte[1024 * 1024];MemoryStream memoryStream2 = new MemoryStream(buffered);//操作memoryStream0.Read(buffered, 0, buffered.Length);memoryStream1.Write(buffered, 0, buffered.Length);//SeekOrigin.Begin//SeekOrigin.Current;//SeekOrigin.End;memoryStream2.Seek(2, SeekOrigin.Begin); //指定流的开始位置 设置新的位置using (FileStream fws = new FileStream(pathw, FileMode.Open, FileAccess.Write, FileShare.None, buffered.Length)) {memoryStream0.WriteTo(fws); //将缓冲区中的数据写入到文件中 持久化的过程}}
总结:
今天我们主要介绍的是关于文件流FileStream的读写操作以及基于内存的MemoryStream,并通过以上这两种方式我们都实现了对于文件的异步复制,但是我们可以明显看出第二种方式的优势:简单明了并且易于理解且性能优于第一种,下次我们将会带来BufferedStream的基本介绍以及使用!
FileStream的使用相关推荐
- 在SQL Server 2008中配置文件流(FILESTREAM)
SQL Server 2008推出了一个新的特性叫做文件流(FILESTREAM),它使得基于SQL Server的应用程序可以在文件系统中存储非结构化的数据,例如文档.图片.音频.视频等等.文件流主 ...
- 如何启用SQL Server 2008的FILESTREAM特性
如何启用SQL Server 2008的FILESTREAM特性 今天安装SQL Server 2008的时候没有注意,忘记了启用FILESTREAM特性,因为默认情况下FILESTREAM是禁用的. ...
- FileStream 的FileShare一点小认识
C#读写文本文件一般都是用StreamWriter来实现(读书的时候就这样用.毕业后这几年基本也是这样干的),通常代码例如以下: using (StreamWriter sw = new Stream ...
- Sqlserver2008 FileStream解决图片存储问题
Sqlserver2008 FileStream解决图片存储问题 参考文章: (1)Sqlserver2008 FileStream解决图片存储问题 (2)https://www.cnblogs.co ...
- FileStream 和StreamWriter 一起用时
StreamWriter Flush 即可. FileStream Flush 无用. 转载于:https://www.cnblogs.com/runliuv/p/3173454.html
- .NET中的异步编程(四)- IO完成端口以及FileStream.BeginRead
本文首发在IT168 写这个系列原本的想法是讨论一下.NET中异步编程风格的变化,特别是F#中的异步工作流以及未来的.NET 5.0中的基于任务的异步编程模型.但经过三篇文章后很多人对IO异步背后实现 ...
- c#FileStream文件读写(转)
/C#文件流写文件,默认追加FileMode.Append string msg = "okffffffffffffffff"; ...
- FileStream实现多线程断点续传(已封装)
处理文件分片 处理缺失的分片文件 合并分片文件 MD5验证文件 using System; using System.Collections.Generic; using System.IO; usi ...
- 在SharePoint 2010系统中安装RBS FILESTREAM Provider
在SharePoint 2010系统中安装RBS FILESTREAM Provider 这两天在研究怎么写一个RBS Provider,可惜文档实在是很缺乏,基本上除了一篇Spec之外,就只有SQL ...
- Winform中使用FileStream读取文件后,继续操作提示:it is being used by anothor process
场景 使用Winform搭建FTP客户端之后,读取本地某路径下的文件,然后将文件读取进行上传,再删除,在进行删除时提示: System.IO.IOException:The process cannn ...
最新文章
- 使用angularJs ng-repeat做表格合并行效果
- Firefox beta 开始原生支持 Windows 10 ARM64
- java代码读取dbsequence的值_MongoDB自增序列实现 - Java多线程同步 synchronized 用法
- VB.NET中的日期时间转换
- VTK修炼之道23:图像基本操作_灰度图像映射成伪彩色图像(查表法)
- Discovering versions from the identity service failed when creating the password plugin.
- C#中HttpClient使用注意:预热与长连接
- jsap支付_Java命令行界面(第20部分):JSAP
- 如何实现Android平台GB28181前端设备接入
- cesium three性能比较_Go学习_21_Golang代码性能检测Benchmark
- Intel Core Enhanced Core架构/微架构/流水线 (2) - 代表处理器
- 一个基于 SpringBoot+Redis+Vue 仿饿了么外卖系统(后台+移动端),可二次开发接私活!...
- 如何查看MFC源码(转)
- 【C004】VB - 数据文件(一)顺序文件
- 用python手把手教你玩跳一跳小游戏,直接打出高分
- PDF文件怎么旋转保存
- UnityECS-初识
- 安装系统时一直是程序正在启动服务器,全新安装win10卡在安装程序正在启动该怎么办?...
- 中国十大B2C电商站点开发语言调查
- 【学习笔记】Python编程,从入门到实践(自学python心路历程及学习笔记整理)
热门文章
- “办公宝”为什么刷屏了?原来科技产品还可以这样取名
- SQL Server时区
- 高通骁龙865之camera性能深度分析(二)
- 使用PHP获取优酷网视频缩略图
- Matlab数据库编程指南
- JS-9 JS常见内置类;包装类型;Number类方法与实例方法;Math方法;String类常见方法;数组方法(增删改查+遍历+排序);时间Date 构造函数+获取信息+设置信息+获取Unix时间戳
- 我不就是吃点肉,应该没事吧——爬取一座城市里的烤肉店数据(附完整Python爬虫代码)
- K-means聚类后的LSTM-CNN出租车热点区域客流预测
- 传统电商办公系统vs电商管理系统
- 阿里“通义千问”大模型上线!让生成式AI更贴近中国人生活