<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # C# 輸入和輸出 > 原文: [https://zetcode.com/lang/csharp/io/](https://zetcode.com/lang/csharp/io/) 本章專門介紹 C# 中的輸入和輸出。 C# 中的輸入和輸出基于流。 ## C# 流 流是字節序列的抽象,例如文件,輸入/輸出設備,進程間通信管道或 TCP/IP 套接字。 流將數據從一個點傳輸到另一點。 流還能夠處理數據。 例如,他們可以壓縮或加密數據。 在 .NET Framework 中,`System.IO`命名空間包含允許對數據流和文件進行讀寫的類型。 C# 為`File`類中的 I/O 操作提供了高級方法,為`StreamReader`或`StreamWriter`等類提供了較低級的方法。 ## 處理異常 I/O 操作容易出錯。 我們可能會遇到`FileNotFoundException`或`UnauthorizedAccessException`之類的異常。 與 Java 不同,C# 不會強制程序員手動處理異常。 由程序員決定是否手動處理異常。 如果在`try/catch/finally`結構中未手動處理該異常,則該異常由 CLR 處理。 ## 釋放資源 I/O 資源必須釋放。 可以使用`Dispose()`方法在`finally`子句中手動釋放資源。 `using`關鍵字可用于自動釋放資源。 同樣,`File`類中的方法為我們釋放了資源。 ## 示例文本文件 在示例中,我們使用以下簡單文本文件: `thermopylae.txt` ```cs The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece. ``` ## C# `File.ReadAllText` `File`提供了用于創建,復制,刪除,移動和打開單個文件的靜態方法,并有助于創建`FileStream`對象。 > **注意**:`File.ReadAllText()`不適合讀取非常大的文件。 `File.ReadAllText()`打開一個文件,以指定的編碼讀取文件中的所有文本,然后關閉該文件。 `Program.cs` ```cs using System; using System.IO; using System.Text; namespace ReadFileIntoString { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\thermopylae.txt"; var text = File.ReadAllText(path, Encoding.UTF8); Console.WriteLine(text); } } } ``` 該程序讀取`thermopylae.txt`文件的內容,并將其打印到控制臺。 ```cs var text = File.ReadAllText(path, Encoding.UTF8); ``` 我們一次性將整個文件讀成字符串。 在第二個參數中,我們指定編碼。 ```cs $ dotnet run The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece. ``` 這是輸出。 ## C# `File.ReadAllLines` `File.ReadAllLines()`打開一個文本文件,將文件的所有行讀入字符串數組,然后關閉文件。 `File.ReadAllLines()`是一種使用 C# 讀取文件的便捷方法。 處理非常大的文件時,不應使用它。 `Program.cs` ```cs using System; using System.IO; namespace ReadAllLines { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\thermopylae.txt"; string[] lines = File.ReadAllLines(path); foreach (string line in lines) { Console.WriteLine(line); } } } } ``` 該示例將文件中的所有行讀入字符串數組。 我們在`foreach`循環中遍歷數組,并將每一行打印到控制臺。 ## C# 創建文件 `File.CreateText()`創建或打開用于寫入 UTF-8 編碼文本的文件。 如果文件已經存在,則其內容將被覆蓋。 `Program.cs` ```cs using System; using System.IO; namespace CreateFileEx { class Program { static void Main() { var path = @"C:\Users\Jano\Documents\cars.txt"; using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hummer"); sw.WriteLine("Skoda"); sw.WriteLine("BMW"); sw.WriteLine("Volkswagen"); sw.WriteLine("Volvo"); } } } } ``` 在示例中,我們創建一個`cars.txt`文件,并將一些汽車名稱寫入其中。 ```cs using (StreamWriter sw = File.CreateText(path)) ``` `CreateText()`方法創建或打開一個文件,用于寫入 UTF-8 編碼的文本。 它返回一個`StreamWriter`對象。 ```cs sw.WriteLine("Hummer"); sw.WriteLine("Skoda"); ... ``` 我們向流寫入兩行。 ```cs $ cat C:\Users\Jano\Documents\cars.txt Hummer Skoda BMW Volkswagen Volvo ``` 我們已成功將五個汽車名稱寫入文件。 ## C# 創建,最后寫入,最后訪問時間 使用`File`類,我們可以獲取文件的創建,最后寫入和最后訪問時間。 `Exists()`方法確定指定的文件是否存在。 `Program.cs` ```cs using System; using System.IO; namespace FileTimes { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\cars.txt"; if (File.Exists(path)) { Console.WriteLine(File.GetCreationTime(path)); Console.WriteLine(File.GetLastWriteTime(path)); Console.WriteLine(File.GetLastAccessTime(path)); } } } } ``` 如果存在指定的文件,我們將確定其創建,最后寫入和最后訪問時間。 ```cs if (File.Exists(path)) ``` 如果調用方具有所需的權限并且路徑包含現有文件的名稱,則`Exists()`方法返回`true`。 否則為`false`。 如果`path`為`null`,無效路徑或長度為零的字符串,則此方法還返回`false`。 ```cs Console.WriteLine(File.GetCreationTime(path)); Console.WriteLine(File.GetLastWriteTime(path)); Console.WriteLine(File.GetLastAccessTime(path)); ``` 我們得到指定文件的創建時間,上次寫入時間和上次訪問時間。 ```cs $ dotnet run 10/13/2019 1:59:03 PM 10/13/2019 1:59:03 PM 10/13/2019 1:59:03 PM ``` 這是一個示例輸出。 ## C# 復制文件 `File.Copy()`方法將現有文件復制到新文件。 它允許覆蓋同名文件。 `Program.cs` ```cs using System; using System.IO; namespace CopyFileEx { class Program { static void Main(string[] args) { var srcPath = @"C:\Users\Jano\Documents\cars.txt"; var destPath = @"C:\Users\Jano\Documents\cars2.txt"; File.Copy(srcPath, destPath, true); Console.WriteLine("File copied"); } } } ``` 然后,我們將文件的內容復制到另一個文件。 ```cs var srcPath = @"C:\Users\Jano\Documents\cars.txt"; var destPath = @"C:\Users\Jano\Documents\cars2.txt"; ``` 這是源文件和目標文件。 ```cs File.Copy(srcPath, destPath, true); ``` `Copy()`方法復制文件。 第三個參數指定是否應覆蓋文件(如果存在)。 ```cs $ dotnet run File copied ``` This is a sample output. ## C# `IDisposable`接口 流實現`IDisposable`接口。 實現此接口的對象必須盡早手動處理。 這是通過在`finally`塊中調用`Dispose()`方法或利用`using`語句來完成的。 `Program.cs` ```cs using System; using System.IO; namespace ManualRelease { class Program { static void Main(string[] args) { StreamReader sr = null; var path = @"C:\Users\Jano\Documents\thermopylae.txt"; try { sr = new StreamReader(path); Console.WriteLine(sr.ReadToEnd()); } catch (IOException e) { Console.WriteLine("Cannot read file"); Console.WriteLine(e.Message); } catch (UnauthorizedAccessException e) { Console.WriteLine("Cannot access file"); Console.WriteLine(e.Message); } finally { sr?.Dispose(); } } } } ``` 在此示例中,我們從磁盤上的文件讀取字符。 我們手動釋放分配的資源。 ```cs sr = new StreamReader(path); Console.WriteLine(sr.ReadToEnd()); ``` `StreamReader`類用于讀取字符。 其父級實現`IDisposable`接口。 ```cs } catch (IOException e) { Console.WriteLine("Cannot read file"); Console.WriteLine(e.Message); } catch (UnauthorizedAccessException e) { Console.WriteLine("Cannot access file"); Console.WriteLine(e.Message); } ``` 可能的異常在`catch`塊中處理。 ```cs finally { sr?.Dispose(); } ``` 在`finally`塊中,`Dispose()`方法清理資源。 使用空條件運算符時,僅當變量不是`null`時,才調用該方法。 ## C# 使用語句 `using`語句定義一個范圍,在該范圍的末尾將放置一個對象。 它提供了一種方便的語法,可確保正確使用`IDisposable`對象。 `Program.cs` ```cs using System; using System.IO; namespace AutomaticCleanup { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\thermopylae.txt"; using (var sr = new StreamReader(path)) { Console.WriteLine(sr.ReadToEnd()); } } } } ``` 該示例讀取`thermopylae.txt`文件的內容。 資源通過`using`語句釋放。 如果我們不處理 IO 異常,則 CLR 將處理它們。 ## C# `using`聲明 `using`聲明是在`using`關鍵字之后的變量聲明。 它告訴編譯器聲明的變量應放在封閉范圍的末尾。 從 C# 8.0 開始,`using`聲明可用。 `Program.cs` ```cs using System; using System.IO; namespace UsingDeclaration { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\thermopylae.txt"; using var sr = new StreamReader(path); Console.WriteLine(sr.ReadToEnd()); } } } ``` 該示例讀取`thermopylae.txt`文件的內容。 當`sr`變量超出范圍時(在`Main()`方法的末尾),將自動清除資源。 ## C# `MemoryStream` `MemoryStream`是用于處理計算機內存中數據的流。 `Program.cs` ```cs using System; using System.IO; namespace MemoryStreamEx { class Program { static void Main(string[] args) { using var ms = new MemoryStream(6); ms.WriteByte(9); ms.WriteByte(11); ms.WriteByte(6); ms.WriteByte(8); ms.WriteByte(3); ms.WriteByte(7); ms.Position = 0; int rs = ms.ReadByte(); do { Console.WriteLine(rs); rs = ms.ReadByte(); } while (rs != -1); } } } ``` 我們用`MemoryStream`將六個數字寫入存儲器。 然后,我們讀取這些數字并將其打印到控制臺。 ```cs using var ms = new MemoryStream(6); ``` 該行創建并初始化一個容量為六個字節的`MemoryStream`對象。 ```cs ms.WriteByte(9); ms.WriteByte(11); ms.WriteByte(6); ... ``` `WriteByte()`方法在當前位置的當前流中寫入一個字節。 ```cs ms.Position = 0; ``` 我們使用`Position`屬性將光標在流中的位置設置為開頭。 ```cs do { Console.WriteLine(rs); rs = ms.ReadByte(); } while (rs != -1); ``` 在這里,我們從流中讀取所有字節并將其打印到控制臺。 ```cs $ dotnet run 9 11 6 8 3 7 ``` 這是示例的輸出。 ## C# `StreamReader` `StreamReader`從字節流中讀取字符。 默認為 UTF-8 編碼。 `Program.cs` ```cs using System; using System.IO; namespace ReadFileEx { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\thermopylae.txt"; using var sr = new StreamReader(path); while (sr.Peek() >= 0) { Console.WriteLine(sr.ReadLine()); } } } } ``` 我們讀取文件的內容。 這次我們使用`ReadLine()`方法逐行讀取文件。 ```cs while (sr.Peek() >= 0) { Console.WriteLine(sr.ReadLine()); } ``` `Peek()`方法返回下一個可用字符,但不使用它。 它指示我們是否可以再次調用`ReadLine()`方法。 如果沒有要讀取的字符,則返回`-1`。 ## C# 計數行 在下一個示例中,我們將對行進行計數。 `Program.cs` ```cs using System; using System.IO; namespace CountingLines { class Program { static void Main(string[] args) { int count = 0; var path = @"C:\Users\Jano\Documents\thermopylae.txt"; using var sr = new StreamReader(path); while (sr.ReadLine() != null) { count++; } Console.WriteLine("There are {0} lines", count); } } } ``` 我們正在計算文件中的行數。 ```cs while(stream.ReadLine() != null) { count++; } ``` 在`while`循環中,我們使用`ReadLine()`方法從流中讀取一行。 如果到達輸入流的末尾,它將從流或`null`中返回一行。 ```cs $ dotnet run There are 3 lines ``` 該文件有三行。 ## C# `StreamWriter` `StreamWriter`以特定編碼將字符寫入流。 `Program.cs` ```cs using System; using System.IO; namespace WriteToFile { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\newfile.txt"; using var sw = new StreamWriter(path); sw.WriteLine("Today is a beautiful day."); } } } ``` 該示例使用`StreamWriter`將字符串寫入文件。 ```cs using (var sw = new StreamWriter(path)) ``` 我們創建一個新的`StreamWriter`。 默認值是 UTF-8。 `StreamWriter`將路徑作為參數。 如果文件存在,它將被覆蓋; 否則,將創建一個新文件。 ```cs $ dotnet run $ cat C:\Users\Jano\Documents\newfile.txt Today is a beautiful day. ``` 我們已經使用`cat`命令顯示了文件的內容。 ## C# `FileStream` `FileStream`為文件提供流,同時支持同步和異步讀取和寫入操作。 `StreamReader`和`StreamWriter`處理文本數據,而`FileStream`處理字節。 `Program.cs` ```cs using System.IO; using System.Text; namespace FileStreamEx { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents\newfile2.txt"; using var fs = new FileStream(path, FileMode.Append); var text = "Фёдор Михайлович Достоевский\n"; byte[] bytes = new UTF8Encoding().GetBytes(text); fs.Write(bytes, 0, bytes.Length); } } } ``` 我們用俄語西里爾字母寫一些文本到文件中。 ```cs using System.Text; ``` `UTF8Encoding`類位于`System.Text`命名空間中。 ```cs using var fs = new FileStream(path, FileMode.Append); ``` 創建一個`FileStream`對象。 第二個參數是打開文件的模式。 附加模式將打開文件(如果存在)并查找到文件末尾,或創建一個新文件。 ```cs var text = "Фёдор Михайлович Достоевский"; ``` 這是俄文西里爾文的文字。 ```cs byte[] bytes = new UTF8Encoding().GetBytes(text); ``` 從俄語西里爾字母文本創建一個字節數組。 ```cs fs.Write(bytes, 0, bytes.Length); ``` 我們將字節寫入文件流。 ```cs $ cat C:\Users\Jano\Documents\newfile2.txt Фёдор Михайлович Достоевский ``` 我們顯示創建文件的內容。 ## C# `XmlTextReader` 我們可以使用流來讀取 XML 數據。 `XmlTextReader`是用于讀取 C# 中的 XML 文件的類。 該類是僅轉發和只讀的。 我們有以下 XML 測試文件: `languages.xml` ```cs <?xml version="1.0" encoding="utf-8" ?> <languages> <language>Python</language> <language>Ruby</language> <language>Javascript</language> <language>C#</language> </languages> ``` 此文件包含自定義 XML 標記之間的語言名稱。 `Program.cs` ```cs using System; using System.IO; using System.Xml; namespace ReadingXMLFile { public class Program { static void Main() { string path = @"C:\Users\Jano\Documents\languages.xml"; using (var xreader = new XmlTextReader(path)) { xreader.MoveToContent(); while (xreader.Read()) { var node = xreader.NodeType switch { XmlNodeType.Element => String.Format("{0}: ", xreader.Name), XmlNodeType.Text => String.Format("{0} \n", xreader.Value), _ => "" }; Console.Write(node); } } } } } ``` 本示例從 XML 文件讀取數據并將其打印到終端。 ```cs using System.Xml; ``` `System.Xml`命名空間包含與 Xml 讀寫相關的類。 ```cs using (var xreader = new XmlTextReader(path)) ``` 創建一個`XmlTextReader`對象。 它是一種讀取器,可提供對 XML 數據的快速,非緩存且僅前向訪問。 它以文件名作為參數。 ```cs xreader.MoveToContent(); ``` `MoveToContent()`方法移至 XML 文件的實際內容。 ```cs while (xreader.Read()) ``` 該行從流中讀取下一個節點。 如果沒有更多節點,則`Read()`方法返回`false`。 ```cs var node = xreader.NodeType switch { XmlNodeType.Element => String.Format("{0}: ", xreader.Name), XmlNodeType.Text => String.Format("{0} \n", xreader.Value), _ => "" }; Console.Write(node); ``` 在這里,我們打印元素名稱和元素文本。 ```cs $ dotnet run language: Python language: Ruby language: Javascript language: C# ``` 這是示例的輸出。 ## C# 創建,移動目錄 `System.IO.Directory`是一個類,具有用于在目錄和子目錄中創建,移動和枚舉的靜態方法。 `Program.cs` ```cs using System; using System.IO; namespace DirectoryEx { class Program { static void Main(string[] args) { Directory.CreateDirectory("temp"); Directory.CreateDirectory("newdir"); Directory.Move("temp", "temporary"); } } } ``` 我們創建兩個目錄,然后重命名其中一個目錄。 目錄在項目文件夾中創建。 ```cs Directory.CreateDirectory("temp"); ``` `CreateDirectory()`方法創建一個新目錄。 ```cs Directory.Move("temp", "temporary"); ``` `Move()`方法為指定的目錄提供一個新名稱。 ## C# `DirectoryInfo` `DirectoryInfo`公開了用于在目錄和子目錄中創建,移動和枚舉的實例方法。 `Program.cs` ```cs using System; using System.IO; namespace ShowContents { class Program { static void Main(string[] args) { var path = @"C:\Users\Jano\Documents"; var dirInfo = new DirectoryInfo(path); string[] files = Directory.GetFiles(path); DirectoryInfo[] dirs = dirInfo.GetDirectories(); foreach (DirectoryInfo subDir in dirs) { Console.WriteLine(subDir.Name); } foreach (string fileName in files) { Console.WriteLine(fileName); } } } } ``` 我們使用`DirectoryInfo`類遍歷特定目錄并打印其內容。 ```cs var path = @"C:\Users\Jano\Documents"; var DirInfo = new DirectoryInfo(path); ``` 我們顯示指定目錄的內容。 ```cs string[] files = Directory.GetFiles(path);; ``` 我們使用靜態`GetFiles()`方法獲取目錄的所有文件。 ```cs DirectoryInfo[] dirs = dir.GetDirectories(); ``` 我們得到所有目錄。 ```cs foreach (DirectoryInfo subDir in dirs) { Console.WriteLine(subDir.Name); } ``` 在這里,我們遍歷目錄并將其名稱打印到控制臺。 ```cs foreach (string fileName in files) { Console.WriteLine(fileName); } ``` 在這里,我們遍歷文件數組并將其名稱打印到控制臺。 在本章中,我們介紹了 C# 中的輸入/輸出操作。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看