在C# WinForm中,可以使用.NET Framework提供的類庫來實現文件操作。這里有一些常見的文件操作示例:
using System;
using System.IO;
namespace FileOperation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnReadFile_Click(object sender, EventArgs e)
{
string filePath = "example.txt";
if (File.Exists(filePath))
{
using (StreamReader sr = new StreamReader(filePath))
{
string content = sr.ReadToEnd();
MessageBox.Show(content);
}
}
else
{
MessageBox.Show("文件不存在!");
}
}
}
}
private void btnWriteFile_Click(object sender, EventArgs e)
{
string filePath = "output.txt";
string content = "Hello, World!";
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine(content);
}
MessageBox.Show("文件已寫入!");
}
private void btnCreateFolder_Click(object sender, EventArgs e)
{
string folderPath = @"C:\example_folder";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
MessageBox.Show("文件夾已創建!");
}
else
{
MessageBox.Show("文件夾已存在!");
}
}
private void btnDeleteFolder_Click(object sender, EventArgs e)
{
string folderPath = @"C:\example_folder";
if (Directory.Exists(folderPath))
{
Directory.Delete(folderPath, true); // 第二個參數表示是否刪除子目錄和文件
MessageBox.Show("文件夾已刪除!");
}
else
{
MessageBox.Show("文件夾不存在!");
}
}
private void btnListFiles_Click(object sender, EventArgs e)
{
string folderPath = @"C:\example_folder";
if (Directory.Exists(folderPath))
{
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
{
MessageBox.Show(file);
}
}
else
{
MessageBox.Show("文件夾不存在!");
}
}
這些示例展示了如何在C# WinForm應用程序中執行基本的文件操作。你可以根據需要修改這些代碼以滿足你的需求。