C# FileStream简单介绍和使用
作者:Kaivin.bao 时间:2023-07-05 23:04:05
本章讲述:FileStream类的基本功能,以及简单示例;
1、引用命名空间:using System.IO;
2、注意:使用IO操作文件时,要注意流关闭和释放问题!
强力推荐:将创建文件流对象的过程写在using当中,会自动帮助我们释放资源;
使用try{} catch(Exception ex){} 进行一次捕获;
3、FileStream 操作字节,可以操作任何类型的文件;下面来简单介绍FileStream类的方法和参数:
(1)FileStream() 作用:创建FileStream对象,参数:第一个是路径,第二个是文件模式FileMode枚举,第三个数据模式FileAcess
FileStream(String, FileMode):
FileStream(String, FileMode, FileAccess)
FileStream(String, FileMode, FileAccess, FileShare)
FileStream(String, FileMode, FileAccess, FileShare, Int32)
初始化FileStream时使用包含文件共享属性(System.IO.FileShare)的构造函数比使用自定义线程锁更为安全和高效
(2)FileMode(以何种方式打开或者创建文件):CreateNew(创建新文件)、Create(创建并覆盖)、Open(打开)、OpenOrCreate(打开并创建)、Truncate(覆盖文件)、Append(追加);
(3)FileAcess(文件流对象如何访问该文件):Read(只读) 、Write(写)、ReadWirte(读写);
(4)FileShare(进程如何共享文件):None(拒绝共享)、Read 、Write、ReadWrite(同时读写)、Delete;
(5)bufferSize(缓冲区大小设置)
4、Stream.Read(array<Byte[], Int32, Int32):从流中读取一块字节,并将数据写入给定的缓冲区;
5、Stream.Write(array<Byte[], Int32, Int32):使用缓冲区中的数据将字节块写入此流;
6、close():关闭当前流并释放与当前流关联的任何资源(如套接字和文件句柄);
7、dispose():释放流所有使用的资源;
8、CopyTo(Stream):从当前流中读取所有字节并将其写入目标流。
CopyTo(Stream, Int32):从当前流中读取所有字节,并使用指定的缓冲区大小将它们写入目标流
9、Seek()(FileStream类维护内部文件指针,该指针指向文件中进行下一次读写操作的位置):将此流的当前位置设置为给定值。(stream.seek(Int64,SeekOrigin)
第一个参数规定文件指针以字节为单位的移动距离。第二个参数规定开始计算的起始位置;SeekOrigin枚举包含3个值:Begin、Current 和 End;
例如:aFile.Seek(0, SeekOrigin.End);
10、由于设置了文件共享模式为允许随后写入,所以即使多个线程同时写入文件,也会等待之前的线程写入结束之后再执行,而不会出现错误
using (FileStream logFile = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
11、简单示例1:简单文件写入
FileStream devStream = new FileStream(devPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite,512);
devStream.Write(data, 0, 128);
if(devStream != null)
devStream.Close();
12、简单示例2:以追加的方式写入文件
public static class MonitData
{
public static string devPath = string.Empty;
private static object objLock = new object();
public static void WriteInfo(byte[] data)
{
lock (objLock)
{
if (!string.IsNullOrEmpty(devPath))
{
byte[] byteArray = new byte[128];
Array.Copy(data, 0, byteArray, 0, 128);
if (byteArray != null && byteArray.Length == 128)
{
using (System.IO.FileStream fs = System.IO.File.OpenWrite(devPath))
{
fs.Seek(0, SeekOrigin.End);
fs.Write(byteArray, 0, byteArray.Length);
fs.Close();
fs.Dispose();
}
}
}
}
}
}
13、简单示例:文件流写入
public static void Main(string[] args)
{
String str = @"E:\下载\软件";
Stopwatch sw = new Stopwatch();
sw.Start();
using (FileStream fsWriter = new FileStream(str + @"\opencv-3.0.exe", FileMode.Create, FileAccess.Write))
{
using (FileStream fsReader = new FileStream(str + @"\opencv-2.4.9.exe", FileMode.Open, FileAccess.Read))
{
byte[] bytes=new byte[1024*4];//4kB是合适的;
int readNum;
while((readNum=fsReader.Read(bytes,0,bytes.Length))!=0)//小于说明读完了
{
fsWriter.Write(bytes,0,readNum);
fsWriter .Flush();//清除缓冲区,把所有数据写入文件中
fsWriter.Close();
fsWriter.Dispose();
}
}
}
sw.Stop();
Console.WriteLine("总的运行时间为{0}",sw.ElapsedMilliseconds);
Console.ReadKey();
}
14、简单示例:读取文件
public static string FileStreamReadFile(string filePath)
{
byte[] data = new byte[100];
char[] charData = new char[100];
FileStream file = new FileStream(filePath, FileMode.Open);
//文件指针指向0位置
file.Seek(0, SeekOrigin.Begin);//可以设置第一个参数
//读入两百个字节
file.Read(data, 0, (int) file.Length);
//提取字节数组
Decoder dec = Encoding.UTF8.GetDecoder();
dec.GetChars(data, 0, data.Length, charData, 0);
file.Close();
file.Dispose();
return Convert.ToString(charData);
}
来源:https://blog.csdn.net/BYH371256/article/details/89331814
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JAVA IDEA 打开assert 设置方式
![](https://img.aspxhome.com/file/2023/7/77137_0s.png)
Android实现手机游戏隐藏虚拟按键
MVC设定默认路由为指定的Area下的某个action
VS2015为console.readkey添加代码片段的方法
![](https://img.aspxhome.com/file/2023/3/108693_0s.png)
解决Properties属性文件中的值有等号和换行的小问题
Android实例HandlerThread源码分析
SpringBoot应用线上重启脚本的命令详解
IOS开发向右滑动返回前一个页面功能(demo)
![](https://img.aspxhome.com/file/2023/5/96015_0s.gif)
java实现1M图片压缩优化到100kb实现示例
![](https://img.aspxhome.com/file/2023/6/88146_0s.png)
Android中子线程和UI线程通信详解
java多线程Synchronized实现可见性原理解析
![](https://img.aspxhome.com/file/2023/6/71216_0s.jpg)
MyBatis学习教程(四)-如何快速解决字段名与实体类属性名不相同的冲突问题
Android自定义实现图片加文字功能
![](https://img.aspxhome.com/file/2023/6/88726_0s.png)
详解用Spring Boot Admin来监控我们的微服务
C#中WebBrowser.DocumentCompleted事件多次调用问题解决方法
Springmvc Controller接口代码示例
Java基础学习之关键字和变量数据类型的那些事
![](https://img.aspxhome.com/file/2023/8/67988_0s.jpg)
使用SmtpClient发送邮件的方法
详解SpringBoot修改启动端口server.port的四种方式
C# 获取指定QQ头像绘制圆形头像框GDI(Graphics)的方法
![](https://img.aspxhome.com/file/2023/4/72484_0s.gif)