一、File
1、File為靜態類
File類,是一個靜態類,支持對文件的基本操作,包括創建,拷貝,移動,刪除和打開一個文件。File類方法的參量很多時候都是路徑path。主要提供有關文件的各種操作,在使用時需要引用System.IO命名空間。
常用的方法
二、FileStream
FileStream文件流 只能處理原始字節(raw byte)。FileStream 類可以用於任何數據文件,而不僅僅是文本文件。FileStream 對象可以用於讀取諸如圖像和聲音的文件,FileStream讀取出來的是字節數組,然后通過編碼轉換將字節數組轉換成字符串。
string str = "今天天氣好晴朗,處處好風光"; byte[] buttf = Encoding.Default.GetBytes(str); //文件流的寫入 using (FileStream fscreat = new FileStream(path, FileMode.Append, FileAccess.Write)) { fscreat.Write(buttf, 0, buttf.Length); }
三、StreamWriter
StreamWriter 類主要用於向流中寫入數據
屬性或方法 | 作用 |
---|---|
bool AutoFlush | 屬性,獲取或設置是否自動刷新緩沖區 |
Encoding Encoding | 只讀屬性,獲取當前流中的編碼方式 |
void Close() | 關閉流 |
void Flush() | 刷新緩沖區 |
void Write(char value) | 將字符寫入流中 |
void WriteLine(char value) | 將字符換行寫入流中 |
Task WriteAsync(char value) | 將字符異步寫入流中 |
Task WriteLineAsync(char value) | 將字符異步換行寫入流中 |
class Program { static void Main(string[] args) { string path = @"D:\\code\\test.txt"; //創建StreamWriter 類的實例 StreamWriter streamWriter = new StreamWriter(path); //向文件中寫入姓名 streamWriter.WriteLine("小張"); //向文件中寫入手機號 streamWriter.WriteLine("13112345678"); //刷新緩存 streamWriter.Flush(); //關閉流 streamWriter.Close(); } }
四、StringWriter
實現用於將信息寫入字符串的 TextWriter。 信息存儲在基礎 StringBuilder 中。
using System; using System.IO; class StringRW { static void Main() { string textReaderText = "TextReader is the abstract base " + "class of StreamReader and StringReader, which read " + "characters from streams and strings, respectively.\n\n" + "Create an instance of TextReader to open a text file " + "for reading a specified range of characters, or to " + "create a reader based on an existing stream.\n\n" + "You can also use an instance of TextReader to read " + "text from a custom backing store using the same " + "APIs you would use for a string or a stream.\n\n"; Console.WriteLine("Original text:\n\n{0}", textReaderText); // From textReaderText, create a continuous paragraph // with two spaces between each sentence. string aLine, aParagraph = null; StringReader strReader = new StringReader(textReaderText); while(true) { aLine = strReader.ReadLine(); if(aLine != null) { aParagraph = aParagraph + aLine + " "; } else { aParagraph = aParagraph + "\n"; break; } } Console.WriteLine("Modified text:\n\n{0}", aParagraph); // Re-create textReaderText from aParagraph. int intCharacter; char convertedCharacter; StringWriter strWriter = new StringWriter(); strReader = new StringReader(aParagraph); while(true) { intCharacter = strReader.Read(); // Check for the end of the string // before converting to a character. if(intCharacter == -1) break; convertedCharacter = Convert.ToChar(intCharacter); if(convertedCharacter == '.') { strWriter.Write(".\n\n"); // Bypass the spaces between sentences. strReader.Read(); strReader.Read(); } else { strWriter.Write(convertedCharacter); } } Console.WriteLine("\nOriginal text:\n\n{0}", strWriter.ToString()); } }