本教程详细介绍如何在不显示任何弹出窗口的情况下,将文件自动保存到预设的目标文件夹中。适合需要批量处理文件或自动化办公流程的用户学习使用。
private string savefile(string content)
{
try
{
// 保存文章内容为html文件
DateTime dt = DateTime.Now;
// 设置文件夹路径
string directory = @D:\;
// 文件名称以时间命名,避免重名
string filename = dt.Year.ToString() +
dt.Month.ToString() +
dt.Day.ToString() +
dt.Hour.ToString() +
dt.Minute.ToString() +
dt.Second.ToString() +
dt.Millisecond.ToString();
// 文件扩展名 可根据具体需要修改
string othername = @.html;
// 文件保存完整路径
string path = directory + filename + othername;
// 验证文件夹是否存在,不存在则创建
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
// 以创建文件的方式写入内容
FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
sw.WriteLine(content);
sw.Close();
fs.Close();
return @D:/ + filename + othername; // 返回文件存储路径
}
catch (Exception ex)
{
// 错误处理
return ;
}
}