Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to add header to the output text file, after reading and writing with a specified condition.

My code reads from input file and writes to the output file:
Ana Teacher 256
Ben Student 12

i want to add header and output file to be:
User Function Points
Ana Teacher 256
Ben Student 123

I tried to read the file and rewrite it with a new line(header).

What I have tried:

C#
string path2 = path + @"\new.txt";
 string s;
 string header = (User, Function, Points);
 string tempfile = path2 + "\\tempfile.txt"; 
//part of code for stream reader, i am not including here

using (StreamWriter writer = new StreamWriter(path))
            {
                 writer.WriteLine(l);

static void InsertHeader(string path2, string header)
{
    var tempfile = Path.GetTempFileName();
    using (var writer = new StreamWriter(tempfile))
    using (var reader = new StreamReader(path2))
    {
        writer.WriteLine(header);
        while (!reader.EndOfStream)
            writer.WriteLine(reader.ReadLine());
    }
    File.Copy(tempfile, path2, true);
    File.Delete(tempfile);
}

 label2.Text = "File is converted ";

}
Posted
Updated 20-Nov-17 9:40am
v5
Comments
Tomas Takac 20-Nov-17 7:17am    
Why do you need to insert the header into an existing file? Why not write header first and then write data?

1 solution

You don't define methods inside methods, and you can't open a stream writer on an open file, and you can't overwrite a file that is being read.

As a suggestion, use File.ReadAllText to read your whole file, then add your header text to that, and write it back over the original file:
C#
string path = @"D:\Temp\MyFile.txt";
string data = File.ReadAllText(path);
string withHeader = "The header\n" + data;
File.WriteAllText(withHeader);
 
Share this answer
 
Comments
anabeth4 20-Nov-17 8:25am    
hm I understand, thanx a lot.
my question is: if I use File.ReadAllText I think it will change all logic, cause i am printing only those lines of text where points are from 100-300.
Where should i include: File.WriteAllText(withHeader); ?? after writing all lines or not?
OriginalGriff 20-Nov-17 8:40am    
Then use ReadAllLines to read the whole file into an array of strings, and build a List of strings to build up the output. Insert your header to the List, and add the lines that are needed to it. Finally, write the List to the file using WriteAllLines:
File.WriteAllLines(path, myList.ToArray());

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900