1

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

Header text to Prepend:

HDR<TableName><DateTime>

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

Please help me how to get the same in both languages VB6.0, C#.NET

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
venkat
  • 5,648
  • 16
  • 58
  • 83

5 Answers5

10

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

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

Community
  • 1
  • 1
yamen
  • 15,390
  • 3
  • 42
  • 52
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)))
user1227804
  • 390
  • 1
  • 5
1
String[] headerLines = new String[]{"HDR<TableName><DateTime>"};
String filename = "1.txt";
var newContent = headerLines.Union(File.ReadAllLines(filename));
File.WriteAllLines(filename, newContent);
Tilak
  • 30,108
  • 19
  • 83
  • 131
-1

VB6 translation of yamen's answer. Air code! I haven't compiled this, much less run it!

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 
MarkJ
  • 30,070
  • 5
  • 68
  • 111
  • And here's some code to find the temporary folder. Just drop in this class from Karl Peterson. http://vb.mvps.org/samples/SysFolders/ – MarkJ May 10 '12 at 02:40
-2

You can do it in the reverse order of the 1st answere, meanse first your write the header in text file then open that text file in append mode and then woirite the data ..for opening the file in append mode use following code line:

   FileStream aFile = new FileStream(filePath, FileMode.Append,
   FileAccess.Write);       
   StreamWriter sw = new StreamWriter(aFile);       
   sw.Write(text);        
   sw.Close();       
   aFile.Close();
Rohit Vyas
  • 1,949
  • 3
  • 19
  • 28
  • Half the question is about managing to do this 'in place', so you need some temp file handling and movement. My answer does the same as yours conceptually (write header first, then write rest) but covers the rest of the question, and doesn't open a file twice for no reason whatsoever. – yamen May 09 '12 at 07:44
  • But in your case you need to explicitly delete the temp file. – Rohit Vyas May 09 '12 at 07:55
  • And how do you plan to do it without a temp file? – yamen May 09 '12 at 07:58
  • Sorry I didn't read the question completely.Data is coming to the text file from other source . So your are right @yamen need to use the temp file. its my bad sorry – Rohit Vyas May 09 '12 at 08:01