c# - 当文件存在时在文件中写入行c#
问题描述
当存在时,我尝试在文件中写入行:
我的代码是下一个:
string strRuta = "C:\File.txt"
if (!Directory.Exists(strRuta))
Directory.CreateDirectory(strRuta);
string psContenido = "Hola";
if (!(File.Exists(strRuta + strNombreArchivo)))
{
swArchivo = File.CreateText(strRuta + strNombreArchivo);
}
if (!psContenido.ToLower().Contains("error"))
{
swArchivo.WriteLine(psContenido);
swArchivo.Flush();
swArchivo.Close();
swArchivo.Dispose();
File.SetCreationTime(strRuta + strNombreArchivo, DateTime.Now);
}
但是当运行这个程序时,我在 WriteLine 中有一个错误,我不明白这是什么原因,你能帮我吗?
我想知道如何在文件中写入(在下一行中)
解决方案
我认为有几个问题。首先,您要指定看起来像文件名的内容并使用该名称创建一个目录(不确定这是否是故意的)。其次,您可以使用类的静态辅助方法AppendAllText
来创建文件(如果文件不存在),并将内容写入文件末尾。它为您处理所有流编写器的内容,因此您不必担心调用 close 和 dispose。File
private static void Main(string[] args)
{
string directory = @"C:\private\temp";
string fileName = "MyFile.txt";
string filePath = Path.Combine(directory, fileName);
string fileContents = "This will be written to the end of the file\r\n";
// This will create the directory if it doesn't exist
Directory.CreateDirectory(directory);
// This will create the file if it doesn't exist, and then write the text at the end.
File.AppendAllText(filePath, fileContents);
File.SetCreationTime(filePath, DateTime.Now);
}
推荐阅读
- javascript - Nodemailer 一直给我一个错误:“TypeError [ERR_INVALID_ARG_TYPE]:“chunk”参数必须是字符串类型或......”
- python - 我有嵌套 dict 变量的列表,需要转换为 Json 对象的 dict 变量类型
- c - 遍历C中具有未知大小结构成员的结构数组
- r - dplyr::select 自制函数中找不到对象
- html - 仅用于字母字符的输入掩码仅允许 1 个单词在 Angular 中使用 Primeng
- rust - 生锈第二次借用的问题
- node.js - 无法在 Docker、Ubuntu 18.04 上运行 Salesforce trailhead 用户界面 API“安装示例应用程序”
- python - 在 paramiko 的 SSH 会话中更改 $PATH
- c# - 微调器的可见性正在获取状态,但在微调器关闭后微调器的不可见性未按预期工作
- animation - Gnuplot Gif 的问题