你的位置:首页 > 软件开发 > ASP.net > .NET中的流

.NET中的流

发布时间:2016-03-08 11:00:09
当应用程序需要和磁盘上的文件打交道的时候,就有了流的概念。流就像架设在应用程序所在内存和磁盘之间的一个管道。 大致思路→ 建立管道 //FileMode.Open打开现有文件,另外还有FileMode.Create, FileMode.Append//Fil ...

 

当应用程序需要和磁盘上的文件打交道的时候,就有了流的概念。流就像架设在应用程序所在内存和磁盘之间的一个管道。

大致思路

Stream是一个基类,抽象类,基本家族成员包括:Stream流的操作有很多,.NET为我们封装了StreamReader和StreamWriter来对流进行操作,我们需要把流作为引用传入。基本用法如下:

 

FileStream from = new FileStream("C:\temp.txt", FileMode.Open, FileAccess.Read);StreamReader reader = new StreamReader(from, Encoding.GetEncoding("GB2312"));...reader.Dispose();
当涉及到二进制的读取和写入时,.NET为我们封装了BinaryReader和BinaryWriter。基本用法如下:

 

public class Book{  public int Id{get;set;}  public string Name{get;set;}  public decimal Price{get;set;}    private string saveFilePath = string.Empty;    public Book(string saveFilePath)  {    this.saveFilePath = saveFilePath;  }    public void SaveBook()  {    FileStream fs = new FileStream(this.saveFilePath, FileMode.Create, FileAccess.Write);    BinaryWriter writer = new BinaryWriter(fs);    writer.Write(this.Id);    writer.Write(this.Name);    writer.Write(this.Price);    writer.Dispose();  }    publci void LoadBook()  {    FileStream fs = new FileStream(this.saveFilePath, 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);  }}var book = new Book("C:\book.txt"){  Id = 1,  Name = "",  Price = 8};book.SaveBook();

 


 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:.NET中的流

关键词:.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。