简体   繁体   中英

Insert row to csv file after the last row

I have a function (is called: writeToCsv ) that inserts rows to csv file.

I run the function row by row.

The problem is: my function inserts the row in the beginning of the file (that's why the previous row is deleted so I never get more than one row).

I want to know how to insert the row after the last row.

Any help appreciated!

var filePath = @"C:\Book1.csv";
// Initialise stream object with file
using (var wr = new StreamWriter(filePath, false, Encoding.UTF8))
{
    // Collection of book titles
    var row = new List<string>();


    // insert Username to Excel
    if (userdetails.username != "")
    {
        row.Add("Username: " + userdetails.username);
    }
    else
    {
        row.Add("Username: Unknown");
    }

    row.Add("");

    var sb = new StringBuilder();

    foreach (string value in row)
    {
        // Add a comma before each string
        // this adds a comma before the book title
        if (sb.Length > 0) {
             sb.Append(",");
        }
        sb = sb.Clear();
        sb.Append(value);
        wr.WriteLine(sb.ToString());
    }
}

change your StreamWriter to append:

using (var wr = new StreamWriter(filePath, true, Encoding.UTF8))

The documentation for your constructor:

public StreamWriter(
    string path,
    bool append,
    Encoding encoding
)

appending the file will write to the end of it, instead of overwriting it.

I recommend you use the File.AppendAllText . As the MSDN docs:

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.

So, you can pass the path os csv file and the content you want to append and it will do for you without need to manage streams objects. There is two overloads:

File.AppendAllText(string path, string contents);

File.AppendAllText(string path, string contents, Encoding encoding);

Since you have the Encoding , use the second overload, for sample:

var rows = new List<string>();

if (userdetails.username != "")
   rows.Add(string.Format("Username: {0}" userdetails.username));
else
   rows.Add("Username: Unknown");

row.Add(string.Empty);

// create the rows you need to append
StringBuilder sb = new StringBuilder();
foreach (string row in rows)
    sb.AppendFormat(",{0}", row);

// flush all rows once time.
File.AppendAllText(filePath, sb.ToString(), Encoding.UTF8);

Your use of StreamWriter isn't really correct. You're, only writing one line. You can change that but changing the instantion to something like;

 using (var wr = new StreamWriter(filePath, true, Encoding.UTF8))

Or, personally, if you don't risk an OutOfMemoryException (meaning your files are too large to hold in memory) I would just simplify the whole thing with;

  List<string> lines = File.ReallAllLines(path);
  lines.Add(String.Join(row, ","));
  File.WriteAllLines(path, lines.ToArray());

It's just so much simpler and easier to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM