温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

FileStream怎么在C#中使用

发布时间:2021-05-17 17:42:40 来源:亿速云 阅读:185 作者:Leah 栏目:编程语言

这篇文章给大家介绍FileStream怎么在C#中使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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);
}

C#是什么

C#是一个简单、通用、面向对象的编程语言,它由微软Microsoft开发,继承了C和C++强大功能,并且去掉了一些它们的复杂特性,C#综合了VB简单的可视化操作和C++的高运行效率,以其强大的操作能力、优雅的语法风格、创新的语言特性和便捷的面向组件编程从而成为.NET开发的首选语言,但它不适用于编写时间急迫或性能非常高的代码,因为C#缺乏性能极高的应用程序所需要的关键功能。

关于FileStream怎么在C#中使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI