Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can we add new row into existing CSV file without header. #1104

Closed
Dushyant262 opened this issue Aug 22, 2018 · 4 comments
Closed

Can we add new row into existing CSV file without header. #1104

Dushyant262 opened this issue Aug 22, 2018 · 4 comments

Comments

@Dushyant262
Copy link

I want to append a record to an existing CSV file so the header is already available. I want to just append a new record into existing CVS file.

Following is my code.
string filePath = "C:\Users\dushyant.patel\Desktop\ExportUtility\123.csv";
StreamWriter writer = new StreamWriter(filePath, true);

SharedDataModel model = new SharedDataModel();
model.SrNo = "17";
model.TypeofEvidence = "Video";

var csv = new CsvWriter(writer);
var record = new List { model };
csv.WriteRecords(record);
writer.Close();
return View();

@Dushyant262 Dushyant262 changed the title Can we add new row without header. Can we add new row into existing CSV file without header. Aug 22, 2018
@Dushyant262
Copy link
Author

Is there any inbuilt method which I can use?

@JoshClose
Copy link
Owner

You would have to read the file then write it again. The reader and writer are forward only. There's no way to edit a file.

You can one file and write to another at the same time though, then delete the old file when done.

@Dushyant262
Copy link
Author

Ok. thanks for your valuable response

@Mattnificent
Copy link

I have been able to append to a file without repeating the header row:

// Do not include the header row if the file already exists
CsvConfiguration csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = !File.Exists(FileName)
};
            
// WARNING: This will throw an error if the file is open in Excel!
using (FileStream fileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
    using (StreamWriter streamWriter = new StreamWriter(fileStream))
    {
        using (var csv = new CsvWriter(streamWriter, csvConfig))
        {
            // Append records to csv
            csv.WriteRecords(recordsToWrite);
        }
    }
}

Note: make sure you build each record in the recordsToWrite collection the same way to avoid column mismatches

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants