C#中流的使用和分类

作者:Darren?Ji 时间:2022-10-04 22:17:41 

使用流读取、写入文件

使用流把文件读取到字节数组:

//FileMode.Create, FileMode.Append
//FileAccess.Write, FileAccess.ReadWrite
//FileMode和FileAccess搭配使用,如果第二个参数FileMode.Appden写追加,第三个参数FileAccess.Read只读,会抛异常
Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read)
byte[] buffer = new byte[source.Length];
int bytesRead = source.Read(buffer, i, (int)source.Length);

Int32类型的最大值,以及Byte, KB, MB, GB转换:

Int32.MaxValue = 2147483647 Byte 
2147483647/1024 = 2097152 KB(1 KB = 1024 Byte) 
2097152/1024 = 2048 MB(1 M = 1024 KB) 
2048/1024 = 2 G(1G = 1024M)

使用流把字节数组写到文件:

Stream target = new FileStream(@"2.jpg", FileMode.Create, FileAccess.Write);

Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read)
byte[] buffer = new byte[source.Length];
int bytesRead = source.Read(buffer, i, (int)source.Length);

target.Write(buffer, 0, buffer.Length);
source.Dispose();
target.Dispose();

使用流对大文件进行分批读取和写入:

int BufferSize = 10240; // 10KB
Stream source = new FileStream(@"D:\a.mp3", FileMode.Open, FileAccess.Read);
Stream target = new FileStream(@"D:\b.mp3", FileMode.Create, FileAccess.Write);

byte[] buffer = new byte[BufferSize];
int byteRead;
do{
   byteRead = source.Read(buffer, 0, BufferSize);
   target.Write(buffer, 0, bytesRead);
} while(byteRead > 0);
target.Dispose();
source.Dispose();

流的分类

在Stream抽象类下包含:
→FileStream→IsolatedStoreageFileStream
→MemoryStream
→NetworkStream

基础流

从流中读取数据:

CanRead()
Read(byte[] buffer, int offset, int count)

向流中写入数据:

CanWrite()
Write(byte[] buffer, int offset, int count)
WriteByte(Byte value)

移动流指针:

CanSeek()
Seek(long offset, SeekOrigion)
Position流的指针位置
Close()
Dispose()
Flush()将缓存设备写入存储设备
CanTimeout()
ReadTimeout()
WriteTimeout()
Length
SetLength(long value)

装饰器流

实现了Decorator模式,包含对Stream抽象基类的引用,同时继承自Stream抽象基类。

  • System.IO.Compression下的DeflateStream和GZipStream用于压缩和解压缩

  • System.Security.Cryptography下的CryptoStream用于加密和解密

  • System.Net.Security下的AuthenticatedStream用于安全性

  • System.IO下的BufferedStream用户缓存

包装器类

不是流类型,而是协助开发者处理流包含的数据,并且不需要将流读取到Byte[]字节数组中。但流的包装器类包含了对流的引用。

StreamReader

继承自TextReader。
将流中的数据读取为字符。

FileStream fs = new FileStream("a.txt", FileMode.Open, FileAcess.Read);
StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GB2312"));

//或者
//StreamReader reader = new StreamReader("a.txt"); //默认采用UTF-8编码方式

StreamWriter

继承自TextWriter。
将字符写入到流中。

string text =
@"aa
bb
cc";

StringReader reader = new StringReader(text);
int c = reader.Read();
Console.Write((char)c);

char[] buffer = new char[8];
reader.Read(buffer, 0, buffer.Length);
Console.Write(String.Join("",buffer));

string line = reader.ReadLine();
Console.WriteLine(line);

string rest = reader.ReadToEnd();
Console.Write();
reader.Dispose();

StringReader和StringWriter

也继承自TextReader和TextWriter,但是用来处理字符串。

BinaryWriter和BinaryReader

BinaryWriter用于向流中以二进制方式写入基元类型,比如int, float, char, string等.BinaryReader用于从流中读取基元类型。注意,这2个类并不是继承TextReader和TextWriter。

namespace ConsoleApplication29
{
   class Program
   {
       static void Main(string[] args)
       {
           Product p = new Product("product.bin")
           {
               Id = 1,
               Name = "GOOD",
               Price = 500F
           };
           p.Save();

Product newP = new Product("product.bin");
           newP.Load();
           Console.WriteLine(newP);
           Console.ReadKey();
       }
   }

public class Product
   {
       public int Id { get; set; }
       public string Name { get; set; }
       public double Price { get; set; }

private string filePath;

public Product(string filePath)
       {
           this.filePath = filePath;
       }

public void Save()
       {
           FileStream fs = new FileStream(this.filePath, FileMode.Create,FileAccess.Write);
           BinaryWriter writer = new BinaryWriter(fs);
           writer.Write(this.Id);
           writer.Write(this.Name);
           writer.Write(this.Price);
           writer.Dispose();
       }

public void Load()
       {
           FileStream fs = new FileStream(this.filePath, FileMode.Open,FileAccess.Read);
           BinaryReader reader = new BinaryReader(fs);
           this.Id = reader.ReadInt32();
           this.Name = reader.ReadString();
           this.Price = reader.ReadDouble();
           reader.Dispose();
       }

public override string ToString()
       {
           return String.Format("Id:{0},Name:{1},Price:{2}", this.Id, this.Name, this.Price);
       }
   }
}

结果:

C#中流的使用和分类

编码方式:
定义了字节如何转换成人类可读的字符或者文本,可以看作是字节和字符的对应关系表。在读取文件采用的编码方式要和创建文件采用的编码方式保持一致。

帮助类

在System.IO命名空间下。

  • File

FileStream fs = File.Create("a.txt");
Open(string path, FileMode mode)
OpenRead()
OpenWrite()
ReadAllText()
ReadAllByte()
WriteBllBytes()
WriteAllLines()
Copy(string sourceFileName, string destFileName)

  • FileInfo

  • Path

  • Directory

  • DirectoryInfo

来源:https://www.cnblogs.com/darrenji/p/3657740.html

标签:C#,流,使用,分类
0
投稿

猜你喜欢

  • Java类加载初始化的过程及顺序

    2021-12-09 16:12:46
  • Android 判断是否连接成功了指定wifi

    2021-10-21 04:59:10
  • C#中Json的简单处理方法

    2022-05-19 05:25:14
  • C#基于委托实现多线程之间操作的方法

    2022-07-16 23:58:16
  • javaweb中Http协议详解

    2022-03-21 05:12:41
  • 使用springboot整合RateLimiter限流过程

    2022-09-12 21:42:48
  • Automapper实现自动映射的实例代码

    2023-08-14 16:37:10
  • Java8实现对List<Integer>的求和

    2023-12-08 07:03:51
  • Android 再按一次返回键退出程序实现思路

    2023-01-07 12:26:36
  • PageHelper插件实现一对多查询时的分页问题

    2021-11-05 07:02:34
  • C#模拟window操作鼠标的方法

    2021-07-17 01:50:22
  • java搜索无向图中两点之间所有路径的算法

    2023-11-10 09:28:26
  • SpringBoot整合Mybatis与thymleft实现增删改查功能详解

    2023-01-06 00:22:59
  • Android 开发之BottomBar+ViewPager+Fragment实现炫酷的底部导航效果

    2022-01-07 19:39:20
  • android TabHost(选项卡)的使用方法

    2021-08-09 10:08:39
  • Unity 通过LineRenderer绘制两点之间的直线操作

    2021-08-04 04:15:08
  • 解决Android屏幕四周闪现红框的问题

    2023-09-03 19:17:01
  • C#实现加密的几种方法介绍

    2022-12-12 22:38:00
  • 关于C#数强转会不会抛出异常详解

    2021-11-09 05:44:48
  • Spring Boot实现配置文件的自动加载和刷新功能

    2023-07-14 02:26:55
  • asp之家 软件编程 m.aspxhome.com