Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Prepending to beginning of a file

Tags:

c#

file-io

What is the best way to add text to the beginning of a file using C#?

I couldn't find a straightforward way to do this, but came up with a couple work-arounds.

  1. Open up new file, write the text that I wanted to add, append the text from the old file to the end of the new file.

  2. Since the text I want to add should be less than 200 characters, I was thinking that I could add white space characters to the beginning of the file, and then overwrite the white space with the text I wanted to add.

Has anyone else come across this problem, and if so, what did you do?

like image 789
Grace Avatar asked Aug 27 '09 18:08

Grace


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

This works for me, but for small files. Probably it's not a very good solution otherwise.

string currentContent = String.Empty; if (File.Exists(filePath)) {     currentContent = File.ReadAllText(filePath); } File.WriteAllText(filePath, newContent + currentContent ); 
like image 112
Victor Martins Avatar answered Oct 05 '22 13:10

Victor Martins