在C#中,使用WinForms進(jìn)行文件操作主要涉及到以下幾個步驟:
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!");
}
在這個示例中,我們創(chuàng)建了兩個方法:ReadFileContent
用于讀取文件內(nèi)容,WriteFileContent
用于寫入文件內(nèi)容。在WinForms中,我們?yōu)榘粹o的點擊事件添加了處理程序,分別調(diào)用這兩個方法來執(zhí)行文件操作。請確保將filePath
變量設(shè)置為實際文件的路徑。