且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在文本文件中添加标题

更新时间:2023-12-01 15:31:04

请注意,从技术上讲,您不能插入"到文件中并让所有内容向下移动".您能做的***的事情是读取文件并用新行重写它.这是一种有效的方法:

Note that you can't technically 'insert' into a file and have all contents 'shift' down. Best you can do is read the file and rewrite it with a new line. Here's one way to do it efficiently:

static void InsertHeader(string filename, string header)
{
    var tempfile = Path.GetTempFileName();
    using (var writer = new StreamWriter(tempfile))
    using (var reader = new StreamReader(filename))
    {
        writer.WriteLine(header);
        while (!reader.EndOfStream)
            writer.WriteLine(reader.ReadLine());
    }
    File.Copy(tempfile, filename, true);
    File.Delete(tempfile);
}

感谢这个答案这个想法但改进到足以让它值得单独发布.

Credits to this answer for the idea but improved enough to make it worth posting separately.

现在,如果您想要接受表名和日期时间的东西,只需将其添加为第二个函数:

Now if you want something that accepts the table name and date time, just add this as a second function:

static void InsertTableHeader(string filename, string tableName, DateTime dateTime)
{
    InsertHeader(filename, 
                 String.Format("HDR{0}{1:yyyy-MM-dd HH:MM:ss}", 
                 tableName, 
                 dateTime));
}

因此,只需根据需要调用 InsertHeader(filename, "Account", DateTime.Now) 或类似方法.

So just call InsertHeader(filename, "Account", DateTime.Now) or similar as needed.