0

I write/read file text with C#.

My method is:

public static void Save(List<DTOSaveFromFile> Items)
{
    File.WriteAllLines(dataPath, (from i in Items select i.Serialize()).ToArray(), Encoding.Default);
}

This always overrides data and only insert 1 rows. How to insert many rows and don't override before rows.

fds
  • 59
  • 8
  • Can you show some sample input and output? – Patrick Hofman Dec 29 '15 at 10:07
  • Possible duplicate of [How to add new line into txt file](http://stackoverflow.com/questions/8255533/how-to-add-new-line-into-txt-file) – Kunal Kakkad Dec 29 '15 at 10:08
  • Sample input: user1 sampleemail@gmail.com 16:43 – fds Dec 29 '15 at 10:10
  • @fds, I was read your link. I try but it show data in my text file: `System.Linq.Enumerable+WhereSelectListIterator`2[STU.Email.DTOSaveFromFile,System.Char[]] System.Collections.Generic.List`1[System.Char[]]` It not add data. Here my code I was edited: http://pastebin.com/K6AYQdw5 – fds Dec 29 '15 at 10:17

2 Answers2

1

Try the File.AppendAllLines method:

public static void Save(List<DTOSaveFromFile> Items)
{
    File.AppendAllLines(dataPath, (from i in Items select i.Serialize()).ToArray(), Encoding.Default);
}

From MSDN:

Appends lines to a file, and then closes the file.

So, this will prevent the file getting overwritten.

Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
  • I find don't have any File.AppendAllLines, only have File.AppendAllText. If change to File.AppendAllText it's show error like that `Argument 2: cannot convert from 'string[]' to 'string'` – fds Dec 29 '15 at 10:28
  • I'm using .NET 3.5. Thanks. – fds Dec 29 '15 at 10:35
0

Try this

public static void Save(List<DTOSaveFromFile> Items)
{
    using (StreamWriter sw = File.AppendText(path))
    {
        foreach(DTOSaveFromFile d in Items)
            sw.WriteLine(d.Serialize(), Encoding.Default);
    }
}
J3soon
  • 3,013
  • 2
  • 29
  • 49
  • So, File only contains AppendAllText. Do you use StreamWrite? – fds Dec 29 '15 at 10:08
  • Sorry, I was test your update answer but it have error like: `Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable>' to 'string' ` – fds Dec 29 '15 at 10:25
  • 'Try this' answers are discouraged. Your first answer just replaced one word (and that is okay if it fixes the problem). Just explain what you did and where the error was, then future readers can understand what the problem is. – Patrick Hofman Dec 29 '15 at 10:45