第十八章 数据访问(In .net4.5) 之 I/O操作
1. 概述
本章内容包括 文件操作、流操作、读写网络数据 以及 异步I/O操作。
2. 主要内容
2.1 文件操作
① 使用 Drive 和 DriveInfo 访问磁盘信息。
DriveInfo[] drivesInfo = DriveInfo.GetDrives(); foreach (DriveInfo driveInfo in drivesInfo)
{
Console.WriteLine(“Drive {}”, driveInfo.Name);
Console.WriteLine(“ File type: {}”, driveInfo.DriveType); if (driveInfo.IsReady == true)
{
Console.WriteLine(“ Volume label: {}”, driveInfo.VolumeLabel);
Console.WriteLine(“ File system: {}”, driveInfo.DriveFormat);
Console.WriteLine(
“ Available space to current user:{, } bytes”,
driveInfo.AvailableFreeSpace); Console.WriteLine(
“ Total available space: {, } bytes”,
driveInfo.TotalFreeSpace); Console.WriteLine(
“ Total size of drive: {, } bytes “,
driveInfo.TotalSize);
}
}
② 可以使用 DictionaryInfo 和 Dictionary 来操作目录信息。
var directory = Directory.CreateDirectory(@”C:\Temp\ProgrammingInCSharp\Directory”);
var directoryInfo = new DirectoryInfo(@”C:\Temp\ProgrammingInCSharp\DirectoryInfo”);
directoryInfo.Create();
*使用DictionarySecurity可以操作目录权限。
DirectoryInfo directoryInfo = new DirectoryInfo(“TestDirectory”);
directoryInfo.Create();
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.AddAccessRule(
new FileSystemAccessRule(“everyone”,
FileSystemRights.ReadAndExecute,
AccessControlType.Allow));
directoryInfo.SetAccessControl(directorySecurity);
*使用 EnumerateDirectories 代替 GetDirectories,会更有效率。
③ 可以使用 File 和 FileInfo 来操作文件信息。
string path = @”c:\temp\test.txt”; if (File.Exists(path))
{
File.Delete(path);
} FileInfo fileInfo = new FileInfo(path); if (fileInfo.Exists)
{
fileInfo.Delete();
}
④ 可以使用 Path 类来操作路径信息。
string folder = @”C:\temp”;
string fileName = “test.dat”;
string fullPath = Path.Combine(folder, fileName); // Results in C:\\temp\\test.dat
*使用 Path 类 还可以实现使用临时文件来保存信息( GetRandomFileName, GetTempPath, GetTempFileName)
2.2 流操作
① Stream基类
② 编码和解码
编码解码是在字符与字节间的转换操作。
.net平台提供的编码格式包括:UTF-8, ASCII, BigEndianUnicode, Unicode, UTF32 和 UTF7.
使用File类的CreateText、OpenRead、OpenText方法,可以通过返回的StreamWriter、FileStream、StreamReader类,用默认编码的方式快捷的进行转换操作。
③ 使用各种类型的流
使用GZipStream压缩数据
string folder = @»c:\temp»;
string uncompressedFilePath = Path.Combine(folder, “uncompressed.dat”);
string compressedFilePath = Path.Combine(folder, “compressed.gz”);
byte[] dataToCompress = Enumerable.Repeat((byte)’a’, * ).ToArray();
using (FileStream uncompressedFileStream = File.Create(uncompressedFilePath))
{
uncompressedFileStream.Write(dataToCompress, , dataToCompress.Length);
}
using (FileStream compressedFileStream = File.Create(compressedFilePath))
{
using (GZipStream compressionStream = new GZipStream(
compressedFileStream, CompressionMode.Compress))
{
compressionStream.Write(dataToCompress, , dataToCompress.Length);
}
} FileInfo uncompressedFile = new FileInfo(uncompressedFilePath);
FileInfo compressedFile = new FileInfo(compressedFilePath); Console.WriteLine(uncompressedFile.Length); // Displays 1048576
Console.WriteLine(compressedFile.Length); // Displays 1052
使用 BufferedStream 一次读写大块数据(通过内存中的缓冲区读写数据,半阻塞式)
string path = @»c:\temp\bufferedStream.txt»; using (FileStream fileStream = File.Create(path))
{
using (BufferedStream bufferedStream = new BufferedStream(fileStream))
{
using (StreamWriter streamWriter = new StreamWriter(bufferedStream))
{
streamWriter.WriteLine(«A line of text.»);
}
}
}
* 现代操作系统是一个多线程的环境,在其上执行文件操作时(File.Exists不一定可靠),实现完善的异常处理机制是很有必要的。
string path = @”C:\temp\test.txt”; try
{
return File.ReadAllText(path);
}
catch (DirectoryNotFoundException) { }
catch (FileNotFoundException) { }
return string.Empty;
2.3 网络通信
① WebRequest 和 WebResponse
WebRequest request = WebRequest.Create(“http://www.microsoft.com”);
WebResponse response = request.GetResponse(); StreamReader responseStream = new StreamReader(response.GetResponseStream());
string responseText = responseStream.ReadToEnd(); Console.WriteLine(responseText); // Displays the HTML of the website response.Close();
2.4 异步I/O操作
① Async/await
public async Task CreateAndWriteAsyncToFile()
{
using (FileStream stream = new FileStream(“test.dat”, FileMode.Create,
FileAccess.Write, FileShare.None, , true))
{
byte[] data = new byte[];
new Random().NextBytes(data); await stream.WriteAsync(data, , data.Length);
}
}
public async Task ReadAsyncHttpRequest()
{
HttpClient client = new HttpClient();
string result = await client.GetStringAsync(“http://www.microsoft.com”);
}
② 并行操作(Parallel)
public async Task ExecuteMultipleRequestsInParallel()
{
HttpClient client = new HttpClient(); Task microsoft = client.GetStringAsync(“http://www.microsoft.com”);
Task msdn = client.GetStringAsync(“http://msdn.microsoft.com”);
Task blogs = client.GetStringAsync(“http://blogs.msdn.com/”); await Task.WhenAll(microsoft, msdn, blogs); //相比使用三个await更高效
}
3. 总结
① 使用 Drive 和 DriveInfo 操作磁盘。
② 使用Dictionary 和 DictionaryInfo 操作文件夹。
③ 使用 File 和 FileInfo 操作文件。
④ 使用 Path 类来操作路径信息。
⑤ 流是对一组字节的抽象。
⑥ 时刻谨记文件系统是可以同时被多用户操作的。
⑦ 使用WebRequest 和 WebResponse 来进行网络请求操作。
⑧ 异步I/O操作可以提升用户体验和程序的可靠性。
第十八章 数据访问(In .net4.5) 之 I/O操作的更多相关文章
- Spring 4 官方文档学习(十)数据访问之JDBC
说明:未修订版,阅读起来极度困难 1.Spring框架JDBC的介绍 Spring JDBC - who does what? 动作 Spring 你 定义连接参数 是 打开连接 是 指定SQ ...
- Spring 4 官方文档学习(十)数据访问之DAO支持
1.介绍 Spring 中 Data Access Object (DAO)支持 的目标是以一种一致的方式更简单的使用JDBC.Hibernate.JPA或JDO等数据访问技术.可以在前面说的几种数据 ...
- 第二十二章 数据访问(In .net4.5) 之 集合
1. 概述 本章内容包括 .net平台中的集合.如何选择集合 以及 如何实现自定义集合. 2. 主要内容 2.1 使用数组(Array) ]; ; x < arrayOfInt.Length; ...
- 第十九章 数据访问(In .net4.5) 之 处理数据
1. 概述 本章介绍 数据库.Json和Xml.web services 三种介质上的数据操作. 2. 主要内容 2.1 数据库 ① 建立连接 .net平台中的数据连接类都继承自DbConnectio ...
- 第二十一章 数据访问(In .net4.5) 之 序列化
1. 概述 应用程序间传递数据,需要先将数据对象转化为字符流或字节流的形式,然后接收端收到后再转化回原始的数据对象.这就是序列化与反序列化. 本章介绍 .net中的序列化与反序列化.序列化器的种类 以 ...
- 第二十章 数据访问(In .net4.5) 之 使用LINQ
1. 概述 .net3.5中新添加给C#的LINQ查询,提供了直观便捷的数据查询方式.并且支持多种数据源的查询. 本章介绍标准的LINQ操作,如何用最优的方式使用LINQ 以及 LINQ to XML ...
- Spring 4 官方文档学习(十)数据访问之OXM
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/oxm.html Java Object 与 XML ...
- Spring 4 官方文档学习(十)数据访问之ORM
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html 占位用,暂略.
- 使用JDBC构建简单的数据访问层
本教程的目的是使用Java编写的分离的层去访问数据库中的表,这一层通常称为数据访问层(DAL) 使用DAL的最大好处是通过直接使用一些类似insert()和find()的方法简化了数据库的访问操作,而 ...
随机推荐
- 《Code Complete》ch.16 控制循环
WHAT? 反复执行的代码片段(你是第一天学编程吗) WHY? 知道如何使用及何时使用每一种循环是创建高质量软件的一个决定性因素 HOW? 检测位于循环开始/循环结尾 带退出的循环 进入循环 只从一个 ...
- Redis附加功能之Redis流水线pipeline
流水线功能的目的:通过减少客户端与服务器之间的通信次数来提高程序的执行效率. 一.通信 在一般情况下, 用户每执行一个 Redis 命令,客户端与服务器都需要进行一次通信:客户端会将命令请求发送给服务 ...
- Android框架 加载图片 库 Picasso 的使用简介
0 说明 现在Android开源库中有许多图片加载框架,本文以picasso为例,总结下开发过程中的一些优化经验,使用的picasso版本如下 compile 'com.squareup.picass ...
- IIS7.0设置404错误页,返回500状态码
一般在II6下,设置自定义404错误页时,只需要在错误页中选择自定义的页面,做自己的404页面即可.但是在IIS7.0及以上时,设置完404错误页后,会发现状态码返回的是500,并且可能会引起页面乱码 ...
- 慕课网-安卓工程师初养成-2-6 Java中的数据类型
来源:http://www.imooc.com/code/1230 通常情况下,为了方便物品的存储,我们会规定每个盒子可以存放的物品种类,就好比在“放臭袜子的盒子”里我们是不会放“面包”的!同理,变量 ...
- 网站导航不止有hao123!
网址导航对于我们上网而言非常的重要,在一定程度上决定了我们每天都在接触一些什么样的网络信息.我个人一直用的是hao123,总体感觉这个网址导航是非常的不错的,不过网址导航不只只有这一个好的更不只有这一 ...
- Exceeded maximum number of retries. Exceeded max scheduling attempts 3 for instance 7d90eb80-29e2-4238-b658-ade407ff9456. Last exception: [u'Traceback (most recent call last):\n', u' File "/usr/lib/py
Exceeded maximum number of retries. Exceeded max scheduling attempts 3 for instance 7d90eb80-29e2-42 ...
- 【Linux】基于Linux的buffer和cache学习
缓存(cached)是把读取过的数据保存起来,重新读取时若命中(找到需要的数据)就不要去读硬盘了,若没有命中就读硬盘.其中的数据会根据读取频率进行组织,把最频繁读取的内容放在最容易找到的位置,把不再读 ...
- 用python3统计代码行数
今天接到一个电话面试,对方问我在一个项目中维护了多少行代码. 我懵逼了,从来没有统计过啊,怎么还会有这种需求? 当时一脸茫然的想了想,回答了一个,呃...差不多两千多行吧...感觉很心虚 挂完电话之后 ...
- IT职场求生法则(转)
摘要:在IT职场打滚超过10年了,从小小的程序员做到常务副总.相对于其它行业,IT职场应该算比较光明的了,但也陷阱重重,本文说说我的亲身体会,希望大家能在IT职场上战无不胜! 作者:张传波 软件知识大 ...