Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert row in first line of text file?

Tags:

c#

I have a test file that contains

1,2,3
2,3,4
5,6,7

I want to insert this into the first line: A,B,C

So that I get:

A,B,C
1,2,3
2,3,4
5,6,7

How can I do this?

like image 664
Gold Avatar asked Mar 08 '10 13:03

Gold


People also ask

How do you enter a new line in a text file?

It should be: "\n".

How do you insert a row the first line of text in Unix?

Use sed 's insert ( i ) option which will insert the text in the preceding line.

How do you add a line at the beginning of a file in shell script?

Add Text to Beginning of File Using echo and cat Commands Then, we simply output the variable and redirect it to the same file. As you can see above, the new text was added on a new line at the beginning of the file. To add the text at the beginning of the existing first line, use the -n argument of echo.


2 Answers

Similar to the previous answers, but this illustrates how to do what you want to do while minimizing memory consumption. There is no way around reading through the entire file you want to modify, even if you open it in a read/write stream, because you can't "insert" data.

static void WriteABC(string filename)
{
    string tempfile = Path.GetTempFileName();
    using (var writer = new StreamWriter(tempfile))
    using (var reader = new StreamReader(filename))
    {
        writer.WriteLine("A,B,C");
        while (!reader.EndOfStream)
            writer.WriteLine(reader.ReadLine());
    }
    File.Copy(tempfile, filename, true);
}
like image 99
Jake Avatar answered Oct 14 '22 19:10

Jake


I think this answer is easier and faster:

public static void WriteToFile(string Path, string Text)
{
    string content = File.ReadAllText(Path);
    content = Text + "\n" + content;      
    File.WriteAllText(Path, content);
}

Then you can call it:

WriteToFile("yourfilepath", "A,B,C");
like image 34
r.mirzojonov Avatar answered Oct 14 '22 20:10

r.mirzojonov