在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应用程序中执行基本的文件操作。你可以根据需要修改这些代码以满足你的需求。