c#点击事件,会调出本地的txt文件,并可以修改文件里面的内容,并保存
时间: 2024-03-01 07:51:32 浏览: 15
可以使用以下代码实现:
```csharp
private void btnOpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\"; // 设置打开文件对话框的初始目录
openFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; // 设置文件类型过滤器
openFileDialog.FilterIndex = 1; // 设置默认文件类型过滤器
openFileDialog.RestoreDirectory = true; // 设置打开文件对话框是否记忆上次打开的目录
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// 打开文件并读取内容
string filePath = openFileDialog.FileName;
string fileContent = File.ReadAllText(filePath);
// 在文本框中显示文件内容
txtContent.Text = fileContent;
}
}
}
private void btnSaveFile_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtContent.Text))
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; // 设置文件类型过滤器
saveFileDialog.FilterIndex = 1; // 设置默认文件类型过滤器
saveFileDialog.RestoreDirectory = true; // 设置保存文件对话框是否记忆上次保存的目录
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
// 保存文件
string filePath = saveFileDialog.FileName;
File.WriteAllText(filePath, txtContent.Text);
MessageBox.Show("文件保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
else
{
MessageBox.Show("文件内容为空,无法保存!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
```
在点击“打开文件”按钮时,会弹出文件选择对话框,用户选择完文件后,读取文件内容,并将其显示在文本框中。
在点击“保存文件”按钮时,会弹出文件保存对话框,用户选择保存路径后,将文本框中的内容保存到指定文件中。如果文本框中的内容为空,则会提示用户无法保存。