文件处理⚓︎
一、I/O类⚓︎
文件是存储在磁盘中的具有特定名称和目录路径的数据集合,当我们使用程序对文件进行读取或写入时,程序会将文件以数据流(简称流)的形式读入内存中。
我们可以将流看作是通过通信路径传递的字节序列,流主要分为输入流和输出流,输入流主要用于从文件读取数据(读操作),输出流主要用于向文件中写入数据(写操作)。
.NET 在 System.IO
命名空间中包含了各种用于文件操作的类,例如文件的创建、删除、读取、写入等等。
Class | Desciption |
---|---|
BinaryReader | 从二进制流中读取原始数据 |
BinaryWriter | 以二进制格式写入原始数据 |
BufferedStream | 临时存储字节流 |
Directory | 提供对目录的操作的静态方法,如复制、移动、重命名等 |
DirectoryInfo | 提供对目录的操作的实例方法,如复制、移动、重命名等 |
DriveInfo | 提供对有关驱动器的信息的访问 |
File | 提供用于创建、复制、删除、移动和打开单一文件的静态方法,并协助创建 FileStream 对象 |
FileInfo | 提供用于创建、复制、删除、移动和打开文件的属性和实例方法,并且帮助创建 FileStream 对象 |
FileStream | 为文件提供 Stream,既支持同步读写操作,也支持异步读写操作 |
Path | 对包含文件或目录路径信息的 String 实例执行操作,这些操作是以跨平台的方式执行的 |
StreamWriter | 用于向流中写入字符串 |
StreamReader | 用于从流中读取字符串 |
二、读文本文件⚓︎
读文件
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
三、写文本文件⚓︎
写文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace StreamReadWrite
{
class Program
{
static void Main(string[] args)
{
// Get the directories currently on the C drive.
DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("CDriveDirs.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}