在文本文件的顶部添加一行 [英] Add a single line to the top of text file

查看:330
本文介绍了在文本文件的顶部添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序拉取数据并将其附加到文本文件,但我需要了解如何以编程方式查看文本文件的第一行,看看它是否与以下文本匹配:

My app pulls data and appends it to a text file but I need to find out how I can programmatically look at the first line of the text file and see if it matches the following text:


DateTime,VirtualIP,VirtualPort,VirtualName,DestinationIP,DestPort,Status,Desired

DateTime,VirtualIP,VirtualPort,VirtualName,DestinationIP,DestPort,Status,Desired

如果它然后继续做正常的功能(下面的代码段),如果第一行与上面不一样,那么我想插入上面的第一行,而不覆盖目前在那里的什么。我如何做到这一点? (基本上推一切一行,所以我可以添加我想要的第一行)... btw这是保存为csv文件,可以在excel中打开。

If it does then continue doing the normal function (snippet below), if the first line is not the same as above then I want to insert the above in the first line without overwriting whats currently there. How can I do this? (essentially pushing everything one line down so I can add what I want on the first line)...btw this is being saved as a csv file that can be opened in excel.

try
{
    // ...
    for (int j = 0; j < memberStatus.Result.Count; j++)
    {
        VirtualMemberStatus status = memberStatus.Result[j];

        //text += String.Format("Name: {4}, Member: {0}:{1}, Status: {2}, Desired: {3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key);
        text += String.Format("{5},{4},{0},{1},{2},{3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key.Replace(":", ","), DateTime.UtcNow);
    }
}
catch
{
    //ERROR CODE 2
    //MessageBox.Show("Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again.");
    errors += String.Format("{0} Error Code: 2, Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again." + Environment.NewLine, DateTime.UtcNow);

}

this.resultsTextBox.Text = text;

此文件不会被删除很多,但如果它是我想要它有正确的列名称在顶部。即:

This file does not get deleted a lot but in the event that it does I want it to have the correct column names at the top. ie:

DateTime,VirtualIP,VirtualPort,VirtualName,DestinationIP,DestPort,Status,Desired


推荐答案

您需要重写整个文件。

You need to rewrite the whole file.


  1. 开启新的(临时的)档案

  2. 撰写标题行
  3. $ b
  4. 刷新并关闭输出文件

  5. 每个输入行都有$ b
  6. 如果没有错误,请立即移动临时文件(通过重命名)。

  1. open a new (temporary!) file
  2. write header line
  3. for each input line, write line (consider block buffering if performance is a concern)
  4. flush and close output file
  5. ONLY if there were no errors, move the temporary file in-place (by renaming).

此过程可以防止出现问题(IO)错误的过程

This procedure can prevent problems when there is an (IO) error halfway the process

这里是执行这样的事情的代码:

Here is code to do such a thing:

using (var input = new StreamReader("input.txt"))
    using (var output = new StreamWriter("input.txt.temp"))
{
    output.WriteLine("headerline"); // replace with your header :)

    var buf = new char[4096];
    int read = 0;
    do 
    {
        read = input.ReadBlock(buf, 0, buf.Length);
        output.Write(buf, 0, read);
    } while (read > 0);

    output.Flush();
    output.Close();
    input.Close();
}

File.Replace("input.txt.temp", "input.txt", "input.txt.backup");

请注意,示例代码甚至创建了一个备份。一个可能的改进点是明确实例化 FileStream(....,FileMode.CreateNew),以防止覆盖临时文件,如果该名称已存在的文件。

Note that the sample code even creates a backup. One possible point of improvement would be to explicitely instantiate FileStream(...., FileMode.CreateNew) so as to prevent overwriting the temporary file if a file already exists by that name.

另一种解决方案是使用 System.IO.Path.GetTempFileName() 。但是, File.Replace 可能不再有效和原子,因为临时文件夹可能位于另一个卷/文件系统上。

Another solution to that would be, to use System.IO.Path.GetTempFileName(). However, then File.Replace might no longer be efficient and atomic, because the tempfolder might be on another volume/filesystem.

这篇关于在文本文件的顶部添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆