Write data to CSV file - c#

I'm having a question about writing data to a CSV file.
I have a file named test.csv in which are 2 fields > accountnumber and relation ID.
Now I want to add another field next to it: IBAN.
The IBAN is the data from the first row which is validated by the SOAP function BBANtoIBAN.
How can I keep the 2 rows of data accountnumbers and relation IDs in the CSV and add the IBAN in the 3rd row?
This is my code so far:
using (var client = new WebService.BANBICSoapClient("IBANBICSoap"))
{
List<List<string>> dataList = new List<List<string>>();
TextFieldParser parser = new TextFieldParser(#"C:\CSV\test.csv");
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(";");
while (!parser.EndOfData)
{
List<string> data = new List<string>();
string row = parser.ReadLine();
try
{
string resultIBAN = client.BBANtoIBAN(row);
if (resultIBAN != string.Empty)
data.Add(resultIBAN);
else
data.Add("Accountnumber is not correct.");
}
catch (Exception msg)
{
Console.WriteLine(msg);
}
dataList.Add(data);
}
}

I see it as:
StreamReader sr = new StreamReader(#"C:\CSV\test.csv")
StreamWriter sw = new StreamWriter(#"C:\CSV\testOut.csv")
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
try
{
string[] rowsArray = line.Split(';');
string row = rowsArray[0];
string resultIBAN = client.BBANtoIBAN(row);
if (resultIBAN != string.Empty)
{
line +=";"+ resultIBAN;
}
else
{
line +=";"+"Accountnumber is not correct.";
}
}
catch (Exception msg)
{
Console.WriteLine(msg);
}
sw.WriteLine(line)
}
sr.Close();
sw.Close();

I would do something like this to parse the csv file, and add an extra item to the data list:
List<List<string>> dataList = new List<List<string>>();
string filename = #"C:\CSV\test.csv";
using (StreamReader sr = new StreamReader(filename))
{
string fileContent = sr.ReadToEnd();
foreach (string line in fileContent.Split(new string[] {Environment.NewLine},StringSplitOptions.RemoveEmptyEntries))
{
List<string> data = new List<string>();
foreach (string field in line.Split(';'))
{
data.Add(field);
}
try
{
string resultIBAN = client.BBANtoIBAN(data[0]);
if (resultIBAN != string.Empty)
{
data.Add(resultIBAN);
}
else
{
data.Add("Accountnumber is not correct.");
}
}
catch (Exception msg)
{
Console.WriteLine(msg);
}
dataList.Add(data);
}

Related

CSV StreamReader deletes blanks (semicolon)

When I read a CSV (smicolon separated) with this method:
public List<string> LoadCSV()
{
List<string> displayName = new List<string>();
List<string> groupName = new List<string>();
using (StreamReader reader = new StreamReader(#"\\aPath\to\aFile.csv"))
{
while (!reader.EndOfStream)
{
String line = reader.ReadLine();
String[] values = line.Split(';');
displayName.Add(values[0]);
groupName.Add(values[6]);
}
}
return displayName;
}
The blanks in displayName get deleted.
One line in the file:
Adobe Acrobat Standard - (Win XP);16477;2;3657;AD Group;1233xxoo_AcrobatStd;1835
For my understanding, this should give for the line above this result:
Adobe Acrobat Standard - (Win XP)
But it's this:
AdobeAcrobatStandard-(WinXP)
Can somebody help?
It's an OutlookAddin. This is how I run the method:
string bodyText = "RealNames:\n";
foreach (string s in LoadCSV()) {
bodyText += s +"\n";
}
openMail.Body = bodyText;

Compare two csv files in C#

I want to compare two csv files and print the differences in a file. I currently use the code below to remove a row. Can I change this code so that it compares two csv files or is there a better way in c# to compare csv files?
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(System.IO.File.OpenRead(path)))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(csvseperator))
{
string[] split = line.Split(Convert.ToChar(scheidingsteken));
if (split[selectedRow] == value)
{
}
else
{
line = string.Join(csvseperator, split);
lines.Add(line);
}
}
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string line in lines)
writer.WriteLine(line);
}
}
Here is another way to find differences between CSV files, using Cinchoo ETL - an open source library
For the below sample CSV files
sample1.csv
id,name
1,Tom
2,Mark
3,Angie
sample2.csv
id,name
1,Tom
2,Mark
4,Lu
METHOD 1:
Using Cinchoo ETL, below code shows how to find differences between rows by all columns
var input1 = new ChoCSVReader("sample1.csv").WithFirstLineHeader().ToArray();
var input2 = new ChoCSVReader("sample2.csv").WithFirstLineHeader().ToArray();
using (var output = new ChoCSVWriter("sampleDiff.csv").WithFirstLineHeader())
{
output.Write(input1.OfType<ChoDynamicObject>().Except(input2.OfType<ChoDynamicObject>(), ChoDynamicObjectEqualityComparer.Default));
output.Write(input2.OfType<ChoDynamicObject>().Except(input1.OfType<ChoDynamicObject>(), ChoDynamicObjectEqualityComparer.Default));
}
sampleDiff.csv
id,name
3,Angie
4,Lu
Sample fiddle: https://dotnetfiddle.net/nwLeJ2
METHOD 2:
If you want to do the differences by id column,
var input1 = new ChoCSVReader("sample1.csv").WithFirstLineHeader().ToArray();
var input2 = new ChoCSVReader("sample2.csv").WithFirstLineHeader().ToArray();
using (var output = new ChoCSVWriter("sampleDiff.csv").WithFirstLineHeader())
{
output.Write(input1.OfType<ChoDynamicObject>().Except(input2.OfType<ChoDynamicObject>(), new ChoDynamicObjectEqualityComparer(new string[] { "id" })));
output.Write(input2.OfType<ChoDynamicObject>().Except(input1.OfType<ChoDynamicObject>(), new ChoDynamicObjectEqualityComparer(new string[] { "id" })));
}
Sample fiddle: https://dotnetfiddle.net/t6mmJW
If you only want to compare one column you can use this code:
List<string> lines = new List<string>();
List<string> lines2 = new List<string>();
try
{
StreamReader reader = new StreamReader(System.IO.File.OpenRead(pad));
StreamReader read = new StreamReader(System.IO.File.OpenRead(pad2));
string line;
string line2;
//With this you can change the cells you want to compair
int comp1 = 1;
int comp2 = 1;
while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
{
string[] split = line.Split(Convert.ToChar(seperator));
string[] split2 = line2.Split(Convert.ToChar(seperator));
if (line.Contains(seperator) && line2.Contains(seperator))
{
if (split[comp1] != split2[comp2])
{
//It is not the same
}
else
{
//It is the same
}
}
}
reader.Dispose();
read.Dispose();
}
catch
{
}

Removing columns in CSV file using c#

I want to remove a column with a specific value. The code below is what I used to remove a row. Can I reverse this to remove a column?
int row = comboBox1.SelectedIndex;
string verw = Convert.ToString(txtChange.Text);
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(System.IO.File.OpenRead(filepath)))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(","))
{
string[] split = line.Split(',');
if (split[row] == kill)
{
//achter split vul je de rij in
}
else
{
line = string.Join(",", split);
lines.Add(line);
}
}
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string line in lines)
writer.WriteLine(line);
}
Assuming we ignore the subtleties of writing CSV, this should work:
public void RemoveColumnByIndex(string path, int index)
{
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(path))
{
var line = reader.ReadLine();
List<string> values = new List<string>();
while(line != null)
{
values.Clear();
var cols = line.Split(',');
for (int i = 0; i < cols.Length; i++)
{
if (i != index)
values.Add(cols[i]);
}
var newLine = string.Join(",", values);
lines.Add(newLine);
line = reader.ReadLine();
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (var line in lines)
{
writer.WriteLine(line);
}
}
}
The code essentially loads each line, breaks it down into columns, loops through the columns ignoring the column in question, then puts the values back together into a line.
This is an over-simplified method, of course. I am sure there are more performant ways.
To remove the column by name, here is a little modification to your code example.
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(System.IO.File.OpenRead(path)))
{
string target = "";//the name of the column to skip
int? targetPosition = null; //this will be the position of the column to remove if it is available in the csv file
string line;
List<string> collected = new List<string>();
while ((line = reader.ReadLine()) != null)
{
string[] split = line.Split(',');
collected.Clear();
//to get the position of the column to skip
for (int i = 0; i < split.Length; i++)
{
if (string.Equals(split[i], target, StringComparison.OrdinalIgnoreCase))
{
targetPosition = i;
break; //we've got what we need. exit loop
}
}
//iterate and skip the column position if exist
for (int i = 0; i < split.Length; i++)
{
if (targetPosition != null && i == targetPosition.Value) continue;
collected.Add(split[i]);
}
lines.Add(string.Join(",", collected));
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string line in lines)
writer.WriteLine(line);
}

Logical error in writing data in a text file in one column

My Usecase is to read data from a textfile by browsing to the location of the file containing the data to be quoted.the data from the file is save in a list. i use arraylist to get the data and loop through the arraylist and concatenate each string then create output file to store the data in single column as demostrated below
Example of a string:
20050000
40223120
40006523
sample out put:
'20050000',
'40223120',
'40006523'
But my code is currently displaying the output in the format:
'20050000'20050000,
'40223120'20050000,
'40006523'40006523
Pls help.
public List<string> list()
{
List<string> Get_Receiptlist = new List<string>();
String ReceiptNo;
openFileDialog1.ShowDialog();
string name_of_Textfile = openFileDialog1.FileName;
try
{
StreamReader sr = new StreamReader(name_of_Textfile);
{
while ((ReceiptNo = sr.ReadLine()) != null)
{
Get_Receiptlist.Add(ReceiptNo);
} // end while
MessageBox.Show("Record saved in the Data list");// just for testing purpose.
}// end StreamReader
}
catch (Exception err)
{
MessageBox.Show("Cannot read data from file");
}
return Get_Receiptlist;
}
private void button2_Click(object sender, EventArgs e)
{
string single_quotation = "'";
string comma = ",";
string paths = #"C:\Users\sample\Desktop\FileStream\Output.txt";
if (!File.Exists(paths))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(paths))
{
string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
sw.WriteLine(quoted_receipt);
sw.WriteLine(Environment.NewLine);
}//foreach
sw.Close();
MessageBox.Show("Finish processing File");
}//end using
}// end if
}
In your method button2_Click you have bad loop:
string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
sw.WriteLine(quoted_receipt);
sw.WriteLine(Environment.NewLine);
}//foreach
First I'm not even sure its Java ... but if it was Java, then I would replace this fragment with this:
List<String> values = list();
for (int i = 0; i < values.size(); i++)
{
String rec = values.get(i);
StringBuilder quoted_receipt = new StringBuilder();
if (i > 0)
{
// add comma only if the first iteration already passed
quoted_receipt.append(comma);
}
quoted_receipt.append(single_quotation).append(rec).append(single_quotation);
sw.WriteLine(quoted_receipt.toString());
sw.WriteLine(Environment.NewLine);
}

How can I read the Uploaded CSV file without saving it to Server?

Hi all, I have CSV files which are in this format:
**CSV Format1**
||OrderGUID||OrderItemID||Qty||SKUID||TrackingNumber||TotalWeight||DateShipped||DateDelivered||ShippingStatusId||OrderShippingAddressId
||5 ||3 ||2 ||12312||aasdasd ||24 ||2012-12-2010|| || 10025 ||10028
||5 ||4 ||3 ||113123||adadasdasd ||22 ||2012-12-2012|| ||10026 ||10028
**CSV Format2**
||"OrderGUID"||"OrderItemID"||"Qty"||"SKUID"||"TrackingNumber"||"TotalWeight"||"DateShipped"||"DateDelivered"||"ShippingStatusId"||"OrderShippingAddressId"||
||"5" ||"3" ||"2" ||"12312"||"aasdasd" ||"24" ||"2012-12-2010"||"" || "10025" ||"10028"||
||"5" ||"4" ||"3" ||"113123"||"adadasdasd" ||"22" ||"2012-12-2012"|| "2012-12-2010" ||"10026" ||"10028"||
I have to read these files without saving them on the server. Can anyone help me? How can I read this files and insert in my db? How can I trim the special characters from the files?
This is what I am trying to do for the file upload:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ImportTrackingNumber(FormCollection form,HttpPostedFileBase UploadedFile,TrackingNumbersModel Trackingnumbers)
{
if (UploadedFile != null)
{
var allowedExtensions = new[] {".xlsx", ".csv"};
if (UploadedFile.ContentLength > 0)
{
var extension = Path.GetExtension(UploadedFile.FileName);
if (extension == ".xlsx")
{
//Need To code For Excel Files Reading
}
else if (extension == ".csv")
{
//string filename = Path.GetFileName(UploadedFile.PostedFile.InputStream);
StreamReader csvreader = new StreamReader(UploadedFile.FileName);
DataTable dt;
}
}
}
return View();
}
Just an example on how you can read the uploaded file without saving it on the server:
// Use the InputStream to get the actual stream sent.
using (StreamReader csvReader = new StreamReader(UploadedFile.InputStream))
{
while (!csvReader.EndOfStream)
{
var line = csvReader.ReadLine();
var values = line.Split(';');
}
}
This is my code:
public static DataTable GetDataTabletFromCSVFile(HttpPostedFileBase file)
{
DataTable csvDataTable = new DataTable();
// Read bytes from http input stream
var csvBody = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
csvBody = Encoding.UTF8.GetString(binData);
}
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream);
streamWriter.Write(csvBody);
streamWriter.Flush();
memoryStream.Position = 0;
using (TextFieldParser csvReader = new TextFieldParser(memoryStream))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvDataTable.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvDataTable.Rows.Add(fieldData);
}
}
return csvDataTable;
}

Categories