在C#中,使用WinForms進行文件操作主要涉及到以下幾個步驟:
using System.IO;
public string ReadFileContent(string filePath)
{
string content = string.Empty;
try
{
using (StreamReader reader = new StreamReader(filePath))
{
content = reader.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading file: {ex.Message}");
}
return content;
}
public void WriteFileContent(string filePath, string content)
{
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(content);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error writing file: {ex.Message}");
}
}
private void buttonRead_Click(object sender, EventArgs e)
{
string filePath = "path/to/your/file.txt";
string content = ReadFileContent(filePath);
MessageBox.Show(content);
}
private void buttonWrite_Click(object sender, EventArgs e)
{
string filePath = "path/to/your/file.txt";
string content = "Hello, this is a sample text!";
WriteFileContent(filePath, content);
MessageBox.Show("File written successfully!");
}
在這個示例中,我們創建了兩個方法:ReadFileContent
用于讀取文件內容,WriteFileContent
用于寫入文件內容。在WinForms中,我們為按鈕的點擊事件添加了處理程序,分別調用這兩個方法來執行文件操作。請確保將filePath
變量設置為實際文件的路徑。