软件编程
位置:首页>> 软件编程>> C#编程>> C# FileStream简单介绍和使用

C# FileStream简单介绍和使用

作者:Kaivin.bao  发布时间:2023-07-05 23:04:05 

标签:C#,FileStream

本章讲述: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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com