C# System.IO.File类可以新建、拷贝、写入、移动、删除文件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string file = Environment.CurrentDirectory + @"\test.txt";
private void btnCreateAndWriter_Click(object sender, EventArgs e)
{
string dest = Environment.CurrentDirectory + @"\test-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
string content = "测试文本,当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if (File.Exists(file))
{
MessageBox.Show("该文件存在,将先进行备份操作!");
File.Copy(file, dest);
MessageBox.Show("文件备份成功!");
File.WriteAllText(file, content);
MessageBox.Show("新文件创建并写入成功!内容为:" + File.ReadAllText(file));
}
else
{
File.WriteAllText(file, content);
MessageBox.Show("文件创建并写入成功!内容为:" + File.ReadAllText(file));
}
}
private void btnMove_Click(object sender, EventArgs e)
{
if (File.Exists(file))
{
File.Move(file, Environment.CurrentDirectory + @"\new\test" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
MessageBox.Show("文件已经移动!");
}
else
{
MessageBox.Show("文件不存在");
}
}
private void btnDel_Click(object sender, EventArgs e)
{
if(File.Exists(file))
{
File.Delete(file);
MessageBox.Show("文件已删除!");
}
else
{
MessageBox.Show("文件不存在");
}
}
}
}
参考:
https://learn.microsoft.com/zh-cn/dotnet/api/system.io.file?view=net-6.0
https://learn.microsoft.com/zh-cn/dotnet/csharp/programming-guide/file-system/how-to-read-from-a-text-file