fds
fds

Reputation: 59

How to write many rows in text file?

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.

Upvotes: 0

Views: 560

Answers (2)

J3soon
J3soon

Reputation: 3143

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);
    }
}

Upvotes: 0

Fᴀʀʜᴀɴ Aɴᴀᴍ
Fᴀʀʜᴀɴ Aɴᴀᴍ

Reputation: 6251

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.

Upvotes: 1

Related Questions