首页 > 解决方案 > 当文件存在时在文件中写入行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 中有一个错误,我不明白这是什么原因,你能帮我吗?

我想知道如何在文件中写入(在下一行中)

标签: c#file

解决方案


我认为有几个问题。首先,您要指定看起来像文件名的内容并使用该名称创建一个目录(不确定这是否是故意的)。其次,您可以使用类的静态辅助方法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);
}

推荐阅读