sok
sok

Reputation: 632

Adding a new string to the last line of a file

Like the tittle says, I would like to add a new string on the bottom of the file, but somehow, its not working. Hope someone can help me out x___x

      private string add(string asd){
        {string filename = "asd.txt";
        StreamReader reader = new StreamReader(filename);
        StreamWriter write = new StreamWriter(filename);
        string input = null;
        while ((input = reader.ReadLine()) != null)
        {
            write.WriteLine(input);
        }
        reader.Close();
        write.WriteLine(asd);
        write.Close();}

Upvotes: 1

Views: 5277

Answers (3)

GETah
GETah

Reputation: 21459

What about something like:

private string add(string asd){
{
        string filename = "asd.txt";
        string readText = File.ReadAllText(filename );
        File.WriteAllText(filename , createText + asd);
}

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839254

Use File.AppendAllText.

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

Example:

private string Add(string asd) {
    string filename = "asd.txt";
    File.AppendAllText(filename, asd);
}

Upvotes: 8

mfussenegger
mfussenegger

Reputation: 3971

You're writing/reading from the same file at the same time. That won't work. You'll have to create a temporary file to write to.

Upvotes: 2

Related Questions