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?
It should be: "\n".
Use sed 's insert ( i ) option which will insert the text in the preceding line.
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.
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);
}
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With