C#中的讀取和寫入文件
在C#中,檔案輸入和輸出(I/O)操作是許多軟體應用程式的重要組成部分,允許開發者有效地讀取和寫入檔案。 無論您是在儲存資料、記錄應用程式事件,或處理大量的文字或二進位資料,C#都提供了強大的工具來處理檔案。 在Tim Corey的影片《C# 資料存取:文字檔案》中,他詳細演示了這些檔案操作,重點介紹如何使用文字檔案進行資料儲存和檢索。 這篇文章旨在總結Tim在影片中介紹的關鍵概念和技術,為您提供有關C#中檔案I/O操作的實用見解。
簡介
在C#中,檔案輸入和輸出操作對於讀取和寫入文字檔案是必需的。 File類提供了靜態方法來與現有檔案互動或建立新檔案。 StreamWriter通常用於讀取和寫入檔案。 StreamReader逐行讀取檔案,允許您存取每一行文字或字串陣列。 您也可以使用while迴圈來有效地讀取較大的檔案。 StreamWriter類用於將資料寫入檔案,支援寫入字串和陣列。 它可以用於將文字附加到現有檔案或覆蓋整個檔案。像WriteText這樣的方法可以輕鬆處理文字檔案中的資料。
這些操作通常在static void Main方法中執行,您在其中定義檔案路徑。 例如,您可以指定一個檔名並使用StreamWriter寫入單個字串或整個字串陣列。 using語句確保在操作後正確關閉文件,防止資源洩漏。 StreamReader也可以用來逐行讀取檔案,可以處理異常來管理檔案不存在或無法存取時的潛在錯誤。 這些檔案I/O功能使C#成為高效處理檔案的絕佳選擇。
Tim介紹了該主題,重點指出在C#中從文字檔案讀取和寫入資料的簡單性。 他演示了如何僅用幾行程式碼即可完成這些任務,使文字檔案成為資料儲存的可行選擇。
建立一個演示控制台應用程式
Tim首先使用Visual Studio建立了一個名為"TextFileDataAccessDemo"的新控制台應用程式。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace TextFileDataAccessDemo
{
class Program
{
static void Main(string[] args)
{
Console.ReadLine(); // Keeps the console window open to view the output
}
}
}using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace TextFileDataAccessDemo
{
class Program
{
static void Main(string[] args)
{
Console.ReadLine(); // Keeps the console window open to view the output
}
}
}他解釋了使用Console.ReadLine來保持控制台視窗開啟,允許使用者查看輸出。
從文字檔案中讀取
Tim演示如何使用File.ReadAllLines方法從文字檔案中讀取。 他展示了如何處理檔案路徑和使用字串字面值來避免轉義字元。
string filePath = @"C:\demos\test.txt";
List<string> lines = File.ReadAllLines(filePath).ToList();string filePath = @"C:\demos\test.txt";
List<string> lines = File.ReadAllLines(filePath).ToList();File.ReadAllLines方法從指定檔案中讀取所有行,並將其作為字串陣列返回。 Tim將此陣列轉換為列表,以便於操作。
寫入文字檔案
Tim解釋了如何使用File.WriteAllLines方法將資料寫入文字檔案。 他演示了如何向列表新增新行並將更新後的列表寫回檔案。
lines.Add("Sue,Storm,WWIStorm.com");
File.WriteAllLines(filePath, lines);lines.Add("Sue,Storm,WWIStorm.com");
File.WriteAllLines(filePath, lines);此程式碼將新條目新增到列表中,並將整個列表寫回檔案。
建立資料模型並從檔案中填充
Tim建立了一個Person類來表示文字檔案中每個條目的資料結構。
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string URL { get; set; }
}public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string URL { get; set; }
}然後,他讀取檔案並填充Person物件列表。
List<Person> people = new List<Person>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (string line in lines)
{
string[] entries = line.Split(',');
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}List<Person> people = new List<Person>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (string line in lines)
{
string[] entries = line.Split(',');
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}此程式碼讀取每行,按逗號分割,並建立一個Person物件,使用提取的資料。
字串插值
Tim介紹字串插值,這是C# 6.0中的一個功能,簡化了變數和字串的結合過程。 此方法使用{}直接將變數嵌入字串中。
foreach (var person in people)
{
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}");
}foreach (var person in people)
{
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}");
}與使用+運算符的傳統連接相比,該語法更簡潔和高效。

資料驗證
Tim強調在從文字檔案讀取時驗證資料的重要性。他指出假設資料結構的風險,並建議檢查分割條目的長度。
foreach (string line in lines)
{
string[] entries = line.Split(',');
if (entries.Length == 3)
{
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}
else
{
// Handle error
Console.WriteLine("Invalid data format.");
}
}foreach (string line in lines)
{
string[] entries = line.Split(',');
if (entries.Length == 3)
{
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}
else
{
// Handle error
Console.WriteLine("Invalid data format.");
}
}這確保只有具有正確條目數的行才能被處理,避免潛在的運行時錯誤。
將物件新增到列表中
Tim展示了如何將新物件新增到列表中。他使用Person類的匿名實例將新的人物新增到列表中。
people.Add(new Person { FirstName = "Greg", LastName = "Jones", URL = "WOWT.com" });people.Add(new Person { FirstName = "Greg", LastName = "Jones", URL = "WOWT.com" });這會在單行中建立並初始化一個新的people列表中。
將資料寫回文字檔案
Tim解釋了如何將Person物件列表轉換為字串列表,其中每個字串表示檔案中的一行。
List<string> output = new List<string>();
foreach (var person in people)
{
output.Add($"{person.FirstName},{person.LastName},{person.URL}");
}
File.WriteAllLines(filePath, output);List<string> output = new List<string>();
foreach (var person in people)
{
output.Add($"{person.FirstName},{person.LastName},{person.URL}");
}
File.WriteAllLines(filePath, output);此程式碼遍歷Person物件建立CSV字串,並將字串列表寫入檔案中。
結論
Tim Corey的C#檔案I/O操作詳細指南為從文字檔案中讀取和寫入提供了實用的見解。 按照他的例子,開發者可以有效地使用文字檔案來管理資料,並實現健全的資料儲存解決方案。 為了深入理解和親身體驗學習,我強烈建議您觀看Tim Corey的影片,在其中他以現實案例深入探討這些概念。

