Dortík
Dortík

Reputation: 167

C# only writed last string

I have a problem, I am writing some data to file save.txt, but in file is only last item which I write.

This is my code:

SetLine("save.txt", Obchod.numbers[0].ToString(), 5);
SetLine("save.txt", Obchod.numbers[1].ToString(), 6);
SetLine("save.txt", Obchod.numbers[2].ToString(), 7);
SetLine("save.txt", Obchod.numbers[3].ToString(), 8);
SetLine("save.txt", Obchod.numbers[4].ToString(), 9);
SetLine("save.txt", Obchod.numbers[5].ToString(), 10);
SetLine("save.txt", Obchod.numbers[6].ToString(), 11); `

void SetLine(string filename, string text, int linenumber)
{
   using (StreamWriter sw = new StreamWriter(@filename, false))
   {
      for (int i = 0; i < linenumber; i++)
      {

      }

      sw.WriteLine(text);
      sw.Close();
   }
}

Upvotes: 0

Views: 93

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

You are passing false to the StreamWriter-constructor which tells it to not append the text to the file but to overwrite the whole text.

I guess you want to rewrite a textfile and the last parameter indicates which line should be overwritten. Then this should do it:

public static void ReplaceLine(string filename, string text, int linenumber)
{
    string[] allLines = File.ReadAllLines(filename);
    if (allLines.Length < linenumber)
        return; // or ArgumentException?
    allLines[linenumber - 1] = text;
    File.WriteAllLines(filename, allLines);
}

But note that it's not efficient to use this method in a loop since it will always load the file into memory, replaces one line and rewrites the whole file.

Upvotes: 2

wizzardmr42
wizzardmr42

Reputation: 1644

You are closing and reopening the file between each write. Either keep it open or specify a parameter to append to it instead of overwriting (which is default)

Upvotes: 2

Related Questions