文件讀寫(二)利用SteamReader和StreamWrite類處理字符串、FileSystemWatcher、BinaryReader/BinaryWriter

1、讀寫類:

TextReader/TextWriter:文本讀寫,抽象類

TextReader,其派生類:html

  • StreamReader:以一種特定的編碼從字節流中讀取字符。
  • StringReader:從字符串讀取。

TextWriter,其派生類:spring

  • 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.htmlapi

2、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 對象使用的全部資源。

實例:

1、使用的實例StreamReader從文件讀取文本 Read(),Peek()服務器

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

2、調用其ReadAsync()方法以異步方式讀取文件。app

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

3、讀取一行字符。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); } }

4、讀取到一個操做中的文件的末尾。ReadToEnd()async

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

3、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類容許直接將字符和字符串寫入文件ide

//保留文件現有數據,以追加寫入的方式打開d:\file.txt文件
using (StreamWriter sw = new StreamWriter(@"d:\file.txt", true)) { //向文件寫入新字符串,並關閉StreamWriter
    sw.WriteLine("Another File Operation Method"); }

4、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}");

5、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(); } }
相關文章
相關標籤/搜索