1

如何在文本文件中添加/附加现有数据的文本开头。基本上我需要在文本文件中的这些数据之前提供一个标题。此标头是动态数据。请注意,此数据来自外部源或 SQL 包或来自某个地方。因此,在文本文件中获取数据后,我想在文本文件的现有条目/数据中提供用逗号分隔的标题文本。

我有一个文本文件中的示例数据,如下所示:

123,"SAV","CBS123",2010-10-10 00:00:00
456,"CUR","CBS456",2012-02-01 00:00:00

要添加的标题文本:

HDR<TableName><DateTime>

我需要的输出如下: 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 中获得相同的结果

4

5 回答 5

10

请注意,从技术上讲,您不能“插入”到文件中并让所有内容“向下移动”。最好的办法是读取文件并用新行重写它。这是一种有效的方法:

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);
}

归功于这个想法的答案,但改进到足以使其值得单独发布。

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

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)根据需要拨打电话或类似电话。

于 2012-05-09T07:36:15.320 回答
2
var fn = @"c:\temp\log.csv";
var hdr1 = "Account";
var hdr2 = "2012-05-09 12:52:00";
System.IO.File.WriteAllText(fn, System.String.Format("HDR {0} {1}\n{2}", hdr1, hdr2, System.IO.File.ReadAllText(fn)))
于 2012-05-09T07:45:54.723 回答
1
String[] headerLines = new String[]{"HDR<TableName><DateTime>"};
String filename = "1.txt";
var newContent = headerLines.Union(File.ReadAllLines(filename));
File.WriteAllLines(filename, newContent);
于 2012-05-09T07:48:42.187 回答
-1

衙门答案的VB6翻译。航空代码!我没有编译这个,更不用说运行它了!

Sub InsertHeader(ByVal filename As String, ByVal header As String) 
  Dim tempfile As String 
  Dim readUnit As Integer 
  Dim writeUnit As Integer

  tempfile = "c:\tempfile" '' TODO generate better temporary filename - 
                '' here is a link to help with getting path of temporary directory 
                ''  http://vb.mvps.org/samples/SysFolders 

  readUnit = FreeFile 
  Open filename For Input As #readUnit 
  writeUnit = FreeFile 
  Open tempfile For Output As #writeUnit 

  Print #writeUnit, header
  Do Until Eof(readUnit) 
    Dim nextLine As String 
    Line Input #readUnit, nextLine 
    Print #writeUnit, nextLine 
  Loop

  Close readUnit 
  Close writeUnit 

  Kill filename
  FileCopy tempfile, filename 
  Kill tempfile  
End sub 
于 2012-05-10T02:24:06.813 回答
-2

您可以按照第一个答案的相反顺序执行此操作,这意味着首先将标题写入文本文件,然后以追加模式打开该文本文件,然后写入数据..以追加模式打开文件使用以下代码行:

   FileStream aFile = new FileStream(filePath, FileMode.Append,
   FileAccess.Write);       
   StreamWriter sw = new StreamWriter(aFile);       
   sw.Write(text);        
   sw.Close();       
   aFile.Close();
于 2012-05-09T07:42:57.730 回答