添加一个单行文本文件的顶部 [英] Add a single line to the top of text file
问题描述
我的应用程序中提取数据,并将其添加到一个文本文件,但我需要找出我如何可以通过编程的文本文件的第一行,看看它下面的文本相匹配:
日期时间,VirtualIP,VirtualPort,VirtualName,DestinationIP,DestPort,状态,期望
如果它不再继续执行正常功能(下面片段),如果如上述然后我要插入上述第一行中,而不覆盖最新目前存在的第一行是不一样的。我怎样才能做到这一点? (基本上都推一条线下来,我可以加我想要在第一行)......顺便说一句,这是被保存为可以在Excel中打开CSV文件。
尝试
{
// ...
对于(INT J = 0; J< memberStatus.Result.Count; J ++)
{
VirtualMemberStatus状态= memberStatus.Result [J]。
//文字+ =的String.Format(名称:{4},会员:{0}:{1},状态:{2},期望:{3}+ Environment.NewLine,status.Member.Address,状态.Member.Port,status.EffectiveStatus,status.DesiredStatus,virtualKey.Key);
文+ =的String.Format({5},{4},{0},{1},{2},{3}+ Environment.NewLine,status.Member.Address,status.Member.Port,状态.EffectiveStatus,status.DesiredStatus,virtualKey.Key.Replace(:,,),DateTime.UtcNow);
}
}
抓住
{
//错误code 2
//MessageBox.Show("Error发生,请检查设备名称(区分灵敏)和管理员组此错误也可能会出现由于连接丢失,请重试)。;
错误+ =的String.Format({0}错误code:2,发生错误,请检查也可能会出现此错误是由于连接丢失,请重试设备名称(区分灵敏)和管理员组。+环境。换行,DateTime.UtcNow);
}
this.resultsTextBox.Text =文本;
该文件不被删除了很多,但在它的事件中,我希望它有顶部的正确的列名。即:
日期时间,VirtualIP,VirtualPort,VirtualName,DestinationIP,DestPort,状态,期望
您需要重写整个文件。
- 打开一个新的(暂时的!)文件
- 在写标题行
- 在每个输入线,写入线(考虑块缓冲,如果性能是一个问题)
- 刷新和关闭输出文件
- 只有当没有错误,将临时文件就地(通过重命名)。
这过程可以prevent的问题时,有一个(IO)中途遇到错误时的过程是
下面是code做这样的事情:
使用(VAR输入=新的StreamReader(input.txt的))
使用(VAR输出=新的StreamWriter(input.txt.temp))
{
output.WriteLine(headerline); //替换为自己的头:)
VAR BUF =新的char [4096];
INT读= 0;
做
{
读= input.ReadBlock(BUF,0,buf.Length);
output.Write(BUF,0,读);
}而(读大于0);
output.Flush();
output.Close();
input.Close();
}
File.Replace(input.txt.temp,input.txt中,input.txt.backup);
请注意,样品code甚至创建一个备份。改进的一种可能的情况是将明确地实例化的FileStream(....,FileMode.CreateNew)
,以prevent覆盖临时文件,如果文件已经存在该名称。
另一种解决方案,这将是,使用<一href="http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx"><$c$c>System.IO.Path.GetTempFileName()$c$c>.但是,那么 File.Replace
可能不再有效,原子,因为tempfolder可能是另一个卷/文件系统。
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
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.
- open a new (temporary!) file
- write header line
- for each input line, write line (consider block buffering if performance is a concern)
- flush and close output file
- ONLY if there were no errors, move the temporary file in-place (by renaming).
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");
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.
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屋!