文件读写(二)利用SteamReader和StreamWrite类处理字符串、FileSystemWatcher、BinaryReader/BinaryWriter

时间:2023-03-09 21:22:33
文件读写(二)利用SteamReader和StreamWrite类处理字符串、FileSystemWatcher、BinaryReader/BinaryWriter

一、读写类:

TextReader/TextWriter:文本读写,抽象类

TextReader,其派生类:

  • StreamReader:以一种特定的编码从字节流中读取字符。
  • StringReader:从字符串读取。

TextWriter,其派生类:

  • IndentedTextWriter:提供可根据 Tab 字符串标记缩进新行的文本编写器。
  • StreamWriter:以一种特定的编码向流中写入字符。
  • StringWriter:将信息写入字符串, 该信息存储在基础 StringBuilder 中。
  • HttpWriter:提供通过内部 TextWriter 对象访问的 HttpResponse 对象。
  • HtmlTextWriter:将标记字符和文本写入 ASP.NET 服务器控件输出流。 此类提供 ASP.NET 服务器控件在向客户端呈现标记时使用的格式化功能。

BinaryReader/BinaryWriter:二进制读写

  • BinaryReader:用特定的编码将基元数据类型读作二进制值。
  • BinaryWriter:以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。

XmlReader/XmlWriter :XML读写

https://www.cnblogs.com/springsnow/p/9428695.html

二、StreamReader类读文件

构造函数:默认编码为UTF-8

public StreamReader (System.IO.Stream stream, System.Text.Encoding encoding );
public StreamReader (string path, System.Text.Encoding encoding)

实例:

StreamReader srAsciiFromFile =  new StreamReader("C:\\Temp\\Test.txt", System.Text.Encoding.ASCII);
StreamReader srAsciiFromStream = new StreamReader( (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),System.Text.Encoding.ASCII);

属性:

  • BaseStream    返回基础流。
  • CurrentEncoding    获取当前 StreamReader 对象正在使用的当前字符编码。
  • EndOfStream    获取一个值,该值指示当前的流位置是否在流结尾。

方法:

  • Peek()    返回下一个可用字符,但不使用它。
  • Read()    读取输入流中的下一个字符并使该字符位置提升一个字符。
  • Read(Char[], Int32, Int32)    从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区。
  • ReadBlock(Char[], Int32, Int32)    从当前流中读取指定的最大字符数并从指定的索引位置开始将该数据写入缓冲区。
  • ReadLine()    从当前流中读取一行字符并将数据作为字符串返回。
  • ReadToEnd()    读取来自流的当前位置到结尾的所有字符。
  • Close()    关闭 StreamReader 对象和基础流,并释放与读取器关联的所有系统资源。
  • Dispose()    释放由 TextReader 对象使用的所有资源。

实例:

一、使用的实例StreamReader从文件读取文本 Read(),Peek()

using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}

二、调用其ReadAsync()方法以异步方式读取文件。

static async Task Main()
{
await ReadAndDisplayFilesAsync();
} static async Task ReadAndDisplayFilesAsync()
{
String filename = "C:\\s.xml";
Char[] buffer; using (var sr = new StreamReader(filename))
{
buffer = new Char[(int)sr.BaseStream.Length];
await sr.ReadAsync(buffer, 0, (int)sr.BaseStream.Length);
} Console.WriteLine(new String(buffer));
}

三、读取一行字符。ReadLine()

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);
}
}

四、读取到一个操作中的文件的末尾。ReadToEnd()

using (StreamReader sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadToEnd());
}

三、StreamWrite类写文件

构造函数

public StreamWriter (System.IO.Stream stream, System.Text.Encoding encoding);
public StreamWriter (string path, bool append, System.Text.Encoding encoding);

属性:

  • BaseStream    获取同后备存储连接的基础流。
  • Encoding    获取在其中写入输出的 Encoding。
  • FormatProvider    获取控制格式设置的对象。
  • NewLine    获取或设置由当前 TextWriter 使用的行结束符字符串。

方法:

  • Write(**)    将 Boolean 值的文本表示形式写入文本字符串或流。
  • WriteLine(**)    将行结束符的字符串写入文本字符串或流。
  • Close()    关闭当前 StreamWriter 对象和基础流。
  • Flush()    清理当前写入器的所有缓冲区,并使所有缓冲数据写入基础流。

实例:

StreamWriter类允许直接将字符和字符串写入文件

//保留文件现有数据,以追加写入的方式打开d:\file.txt文件
using (StreamWriter sw = new StreamWriter(@"d:\file.txt", true))
{
//向文件写入新字符串,并关闭StreamWriter
sw.WriteLine("Another File Operation Method");
}

四、FileSystemWatcher

构造函数

给定要监视的指定目录和文件类型,初始化 FileSystemWatcher 类的新实例。

public FileSystemWatcher (string path, string filter);

属性

  • EnableRaisingEvents    获取或设置一个值,该值指示是否启用此组件。
  • Filter    获取或设置筛选字符串,用于确定在目录中监视哪些文件。
  • IncludeSubdirectories    获取或设置一个值,该值指示是否监视指定路径中的子目录。
  • NotifyFilter    获取或设置要监视的更改类型。
  • Path    获取或设置要监视的目录的路径。

事件

  • Created    当在指定 Path 中创建文件和目录时发生。
  • Changed    当更改指定 Path 中的文件和目录时发生。
  • Deleted    删除指定 Path 中的文件或目录时发生。
  • Renamed    重命名指定 Path 中的文件或目录时发生。

实例:

下面的示例创建FileSystemWatcher监视在运行时指定的目录。 该组件设置为监视中的更改LastWriteLastAccess时间、 创建、 删除、 或重命名的目录中的文本文件。 如果文件是更改、 创建,或删除,文件的路径将打印到控制台。 在一个文件重命名后,旧的和新路径将打印到控制台。

static void Main()
{
Run();
} [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private static void Run()
{
// Create a new FileSystemWatcher and set its properties.
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = "C:\\aa\\"; // Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files.
watcher.Filter = "*.txt"; // Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed; // Begin watching.
watcher.EnableRaisingEvents = true; // Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
} // Define the event handlers.
// Specify what is done when a file is changed, created, or deleted.
private static void OnChanged(object source, FileSystemEventArgs e) => Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
// Specify what is done when a file is renamed.
private static void OnRenamed(object source, RenamedEventArgs e) => Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");

五、BinaryReader/BinaryWriter

读写流的基元数据类型。可以操作图像、压缩文件等二进制文件。不需要一个字节一个字节进行操作,可以是2个、4个、或8个字节这样操作。可以将一个字符或数字按指定数量的字节进行写入。

写入:

using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}

读取:

每次读取都回提升流中的当前位置相应数量的字节。下面的代码示例演示了如何存储和检索文件中的应用程序设置。

const string fileName = "AppSettings.dat";
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar; if (File.Exists(fileName))
{
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
} Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}

BinaryReader读取图片:

using (FileStream fs = new FileStream("1.jpg", FileMode.Open, FileAccess.Read))
{//将图片以文件流的形式进行保存
using (BinaryReader br = new BinaryReader(fs))
{
byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
br.Close();
}
}