Reputation: 59
I have wrote this code to read and write to a CSV file. Is there any way that I could skip writing the first row as its headers and I want to write my own headers to the new file. This is what I have done so far
try
{
using (StreamWriter sw = new StreamWriter("C:/Projects/data/PYAEGON1AEGONRESULT.csv"))
using (StreamReader sr = new StreamReader("C:/Projects/data/PYAEGON1AEGON.csv"))
{
heading = "Title, First Name, Surname, Date Of Birth, NI Number, Gender, Payroll Reference, Address Line 1, Address Line 2, Address Line 3, Address Line 4, AddressLine 5, PostCode, Country, Email, Date Joined Employer, Annual Pensionable Salary, Current Period All Earnings (Monthly), Current Period Pensionable Earnings (Monthly), Emnployee (Amount Deducted), Employer (Amount Deducted), Leaving Date.";
sw.WriteLine(heading);
while((txtline = sr.ReadLine()) != null)
{
oldcolumns = Regex.Split(txtline,",");
newcolumns[0] = oldcolumns[0];
newcolumns[1] = oldcolumns[1];
newcolumns[2] = oldcolumns[2];
newcolumns[3] = oldcolumns[3];
newcolumns[4] = oldcolumns[4];
newcolumns[5] = oldcolumns[5];
newcolumns[6] = oldcolumns[6];
newcolumns[7] = oldcolumns[7];
newcolumns[8] = oldcolumns[9];
newcolumns[9] = oldcolumns[10];
newcolumns[10] = oldcolumns[11];
newcolumns[11] = "";
newcolumns[12] = oldcolumns[12];
newcolumns[13] = "United Kingdom";
newcolumns[14] = oldcolumns[14];
newcolumns[15] = oldcolumns[15];
newcolumns[16] = oldcolumns[16];
newcolumns[17] = oldcolumns[17];
newcolumns[18] = oldcolumns[18];
newcolumns[19] = oldcolumns[19];
newcolumns[20] = oldcolumns[20];
newcolumns[21] = "";
csvline = "";
for (int i = 0; i < 21; i++)
{
csvline = csvline + "\"" + newcolumns[i].Replace("\"","") + "\",";
}
sw.WriteLine(csvline);
}
Upvotes: 0
Views: 1247
Reputation: 156968
Just call sr.ReadLine()
before you actually start reading the input.
using (StreamWriter sw = new StreamWriter("C:/Projects/data/PYAEGON1AEGONRESULT.csv"))
using (StreamReader sr = new StreamReader("C:/Projects/data/PYAEGON1AEGON.csv"))
{
sr.ReadLine();
// rest of your code
Upvotes: 0
Reputation: 460108
If you don't want to write the first line use sr.ReadLine()
once before you start writing. This advances the reader to the second line.
using (StreamWriter sw = new StreamWriter("C:/Projects/data/PYAEGON1AEGONRESULT.csv"))
using (StreamReader sr = new StreamReader("C:/Projects/data/PYAEGON1AEGON.csv"))
{
sr.ReadLine();
// the next ReadLine will read the second line as desired
heading = "Title, First Name, Surname, Date Of Birth, NI Number, Gender, Payroll Reference, Address Line 1, Address Line 2, Address Line 3, Address Line 4, AddressLine 5, PostCode, Country, Email, Date Joined Employer, Annual Pensionable Salary, Current Period All Earnings (Monthly), Current Period Pensionable Earnings (Monthly), Emnployee (Amount Deducted), Employer (Amount Deducted), Leaving Date.";
sw.WriteLine(heading);
while((txtline = sr.ReadLine()) != null)
{
// ...
sw.WriteLine(csvline);
// ...
Upvotes: 1