如何在文本文件中添加标题 [英] How to prepend a header in a text file
问题描述
如何在文本文件中的现有数据的开头添加/附加文本.基本上我需要在文本文件中的这些数据之前提供一个标题.这个头是一个动态数据.请注意,此数据来自外部源或 SQL 包或来自某个地方.因此,在文本文件中获取数据后,我想在文本文件的现有条目/数据中提供一个用逗号分隔的标题文本.
How to prepend/append text beginning of the existing data in a text file. Basically i need to provide a header before this data in a text file. This header is a dynamic data. Please note this data is coming from external source or SQL package or from somewhere. So After getting data in a text file then i want to provide a header text with comma separated in the existing entries/data of a text file.
我在文本文件中的示例数据如下:
I've sample data in a text file as below:
123,"SAV","CBS123",2010-10-10 00:00:00
456,"CUR","CBS456",2012-02-01 00:00:00
要添加的标题文本:
HDR<TableName><DateTime>
我需要的输出如下:表名:帐户日期时间:2012-05-09 12:52:00
Output i need as below: TableName: Account DateTime: 2012-05-09 12:52:00
HDRAccount2012-05-09 12:52:00
123,"SAV","CBS123",2010-10-10 00:00:00
456,"CUR","CBS456",2012-02-01 00:00:00
请帮助我如何在两种语言中获得相同的 VB6.0、C#.NET
Please help me how to get the same in both languages VB6.0, C#.NET
推荐答案
请注意,从技术上讲,您不能插入"到文件中并让所有内容向下移动".您能做的最好的事情是读取文件并用新行重写它.这是一种有效的方法:
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.
这篇关于如何在文本文件中添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!