26.C# 文件系统
1.流的含义
流是一系列具有方向性的字节序列,比如水管中的水流,只不过现在管道中装的不是水,而是字节序列。当流是用于向外部目标比如磁盘输出数据时称为输出流,当流是用于把数据从外部目标读入程序称为输入流。
2.文件读写
写入
string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.OpenOrCreate,FileAccess.ReadWrite);
string strData = "Hello to you";
byte[] byteData = Encoding.UTF8.GetBytes(strData);
fs.Write(byteData, , byteData.Length);
读取
string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read);
byte[] buffer = new byte[];
int count =;
MemoryStream ms = new MemoryStream();
while ((count = fs.Read(buffer, , buffer.Length)) > )
{
ms.Write(buffer, , buffer.Length);
}
string strData= Encoding.UTF8.GetString(ms.ToArray());
注:File.Open方法不传FileAccess参数时,默认FileAcross.ReadWrite
3.StreamReader/StreamWriter流读写器
FileStream读写文件是直接对字节流进行操作的并不能对字符直接进行输入输出,使用StreamReader/StreamWriter可以方便的对字符/字符串进行操作。通常情况下都会把FileStream等其他流包装在StreamReader/StreamWriter中,因为这些类更容易对流进行处理。
3.1读写文本文件
写入
string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Hello to you");
sw.Write("It's now {0}", DateTime.Now.ToString());//格式化字符串
sw.Close();
fs.Close();
读取
string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string lines="";
string line = sr.ReadLine();
lines += line;
while (line!=null)
{
line = sr.ReadLine();
lines += line;
}
txtContent.Text = lines;
sr.Close();
fs.Close();
注:StreamReader/StreamWriter本身不能对文件进行FileMode,FileAccess等权限控制,如果要控制需要在包装的流中进行
StreamReader读取二进制文件
string fileName = Server.MapPath("img\\中文Begrüßung.png");
StreamReader sr = new StreamReader(File.OpenRead(fileName));
byte[] buffer = new byte[];
int count;
MemoryStream ms = new MemoryStream();
while ((count = sr.BaseStream.Read(buffer, , buffer.Length)) > )
{
ms.Write(buffer, , count);
}
string fileName2 = Server.MapPath("img\\中文2.png");
FileStream fs = File.Open(fileName2, FileMode.OpenOrCreate);
ms.WriteTo(fs);
fs.Close();
sr.Close();
StreamReader读取二进制文件需要用到BaseStream,不能像读写文本文件那样,否则保存的文件不能用。
4.对象序列化为二进制数据
程序一般保存的数据都不是像一般的文本文件那样直接写入文本逐行保存的,而是以二进制数据的形式保存的,使用System.Runtime.Serialization.Formatters.Binary.BinaryFormatter可以把对象序列化为二进制数据,或者把二进制数据序列化为对象。
[Serializable]
public class Product
{
public long Id;
public string Name;
public double Price; [NonSerialized]
string Notes; public Product(long id, string name, double price, string notes)
{
this.Id = id;
this.Name = name;
this.Price = price;
this.Notes = notes;
} public override string ToString()
{
return string.Format("{0},{1},${2:F2},{3}",Id,Name ,Price ,Notes);
}
}
序列化/反序列化
List<Product> products = new List<Product>();
products.Add(new Product(, "poky", 10.2, "pokys"));
products.Add(new Product(, "kuti", 2.34, "第四方")); //序列化对象保存到文件
string fileName = Server.MapPath("ser.txt");
FileStream fs = File.Open(fileName, FileMode.OpenOrCreate);
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(fs, products);
fs.Close(); //反序列化
FileStream ls = File.Open(fileName, FileMode.OpenOrCreate);
List<Product> ps = serializer.Deserialize(ls) as List<Product>;
ls.Close();
注:这里是序列化为二进制数据,所以和序列化为Json/xml是不一样的。
5.压缩/解压数据
如果要保存的数据比较大,还可以对数据进行压缩再保存,但是这里的压缩是单纯压缩数据,不是压缩文件,所以和常用的压缩解压工具是不一样的。
public class CompressDAL
{
/// <summary>
/// 创建一个压缩文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="data"></param>
public static void SaveCompressFile(string fileName, string data)
{
FileStream fs = File.Open(fileName, FileMode.Create,FileAccess.Write);
GZipStream gs = new GZipStream(fs, CompressionMode.Compress);
StreamWriter sw = new StreamWriter(gs);//向压缩流写入数据
sw.Write(data);
sw.Close();
} public static string LoadeCompressFile(string fileName)
{
FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read);
GZipStream gs = new GZipStream(fs, CompressionMode.Decompress);
StreamReader sr = new StreamReader(gs);
string lines = sr.ReadToEnd();
return lines;
} }
string data = "叫爸爸\n叫爸爸\n";
string fileName = Server.MapPath("gzFile.txt");
CompressDAL.SaveCompressFile(fileName, data);
string content = CompressDAL.LoadeCompressFile(fileName);
26.C# 文件系统的更多相关文章
- 系统管理员都要知道的 30 个 Linux 系统监控工具
1. top - 进程活动监控命令 top 命令会显示 Linux 的进程.它提供了一个运行中系统的实时动态视图,即实际的进程活动.默认情况下,它显示在服务器上运行的 CPU 占用率最高的任务,并且每 ...
- RHCSA阶段笔记
命令终端字段含义介绍 [root@localhost ~]# 解释: root:当前登录系统用户名(root超级管理员) localhost :当前主机名 :当前用户所在目录( 为家目录) ,root ...
- 射频识别技术漫谈(26)——Felica的文件系统
Felica的文件系统使用“系统\域\服务\数据块”的结构,如下图所示.通过这种结构实现对卡片非易失性存储区的使用和操作. Fe ...
- 26、pathlib文件系统模块(了解)
一.pathlib库官方定义 pathlib 是Python内置库,Python 文档给它的定义是 Object-oriented filesystem paths(面向对象的文件系统路径).path ...
- 26、linux文件系统
- .NET Core的文件系统[5]:扩展文件系统构建一个简易版“云盘”
FileProvider构建了一个抽象文件系统,作为它的两个具体实现,PhysicalFileProvider和EmbeddedFileProvider则分别为我们构建了一个物理文件系统和程序集内嵌文 ...
- Linux学习之探索文件系统
Linux,一起学习进步- ls With it, we can see directory contents and determine a variety of important file ...
- .NET Core的文件系统[1]:读取并监控文件的变化
ASP.NET Core 具有很多针对文件读取的应用.比如我们倾向于采用JSON文件来定义配置,所以应用就会涉及针对配置文件读取.如果用户发送一个针对物理文件的HTTP请求,应用会根据指定的路径读取目 ...
- .NET Core的文件系统[4]:由EmbeddedFileProvider构建的内嵌(资源)文件系统
一个物理文件可以直接作为资源内嵌到编译生成的程序集中.借助于EmbeddedFileProvider,我们可以统一的编程方式来读取内嵌于某个程序集中的资源文件,不过在这之前我们必须知道如何将一个项目文 ...
随机推荐
- GitToc-为你的Github仓库的Readme自动生成一个目录
维护自己的Github仓库的时候发现Github的Readme不支持Toc目录,所以就自己写了一个小工具. 工具地址:https://github.com/Holy-Shine/GitToc 简介 如 ...
- WXS-运算符
- spring添加事物
<context:component-scan base-package="com.zlkj" > <context:include-filter type=&q ...
- 2019年广东省赛gdccpc回顾
本次比赛状态一般般,热身赛单人挂机爆零让自己慌了一整天. 开题直接抓E题入手,准备交题后关机(辣鸡云桌面),开机后又告诉我要关机,心急连交两发结果都WA了,最后靠队员提醒救了回来.心态还算稳住了.后面 ...
- snakemake学习笔记
什么是snakemake? snakemake 是一个流程搭建的工具,这里主要用来记录一些snakemake的使用方法 对于run或者shell部分的需要使用sample变量可以使用wildcards ...
- 双链表的基本实现与讲解(C++描述)
双链表 双链表的意义 单链表相对于顺序表,确实在某些场景下解决了一些重要的问题,例如在需要插入或者删除大量元素的时候,它并不需要像顺序表一样移动很多元素,只需要修改指针的指向就可以了,其时间复杂度为 ...
- [转帖]AWS第一,「3A格局」稳固,活跃IP是如何被全球云厂商瓜分的?
AWS第一,「3A格局」稳固,活跃IP是如何被全球云厂商瓜分的? 本文作者:王刚 2019-02-24 10:42 https://www.leiphone.com/news/201902/qsz3c ...
- [转帖]04-创建kubeconfig认证文件
04-创建kubeconfig认证文件 https://www.cnblogs.com/guigujun/p/8366530.html 学习一下 貌似挺有用的. 本文档记录自己的学习历程! 创建 ku ...
- uwsgi03----直接部署
1.http 和 http-socket的使用上有一些区别: http: 自己会产生一个http进程(可以认为与nginx同一层)负责路由http请求给worker, http进程和worker之间使 ...
- as报错 Multiple root tags Unexpected tokens 这个都是编译器识别问题
从网上复制了个代码,直接复制上,结果一篇红线提示Unexpected tokens 通过去掉空格,还是无法根治,别的地方复制的就没有问题. 通过查看复制的网页源码 可以看到里边<> 这个符 ...