Writing a .CSV file usingt the LinqtoCSV DLL - c#

I'm trying to write to a CSV file from a list using the LinqToCSV library found on http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library#Installation.
When I try and run my program I keep getting a CsvColumnAtrributeRequiredException exception. So it's not filling a CSV file.
Here is my code:
private void button1_Click(object sender, EventArgs e) // merge files button
{
if(System.IO.File.Exists("OUTPUT.csv"))
{
System.IO.File.Delete("OUTPUT.csv");
output = new System.IO.StreamWriter("OUTPUT.csv");
}
else
{
output = new System.IO.StreamWriter("OUTPUT.csv");
}
String[] parts = new String[1000];
String[] parts2 = new String[1000];
parts = File.ReadAllLines(textBox1.Text); //gets filepath from top textbox
parts2 = File.ReadAllLines(textBox2.Text); //gets filepath from middle textbox
String[] head = File.ReadAllLines(headingFileBox.Text); //header file array
//merging the two files onto one list, there is no need to merge the header file because no math is being
//computed on it
var list = new List<String>();
list.AddRange(parts);
list.AddRange(parts2);
//foreach loop to write the header file into the output file
foreach (string h in head)
{
output.WriteLine(h);
}
//prints 3 blank lines for spaces
output.WriteLine();
output.WriteLine();
output.WriteLine("LEASE NAME" + "," + "FIELD NAME" + "," + "RESERVOIR" + "," + "OPERATOR" + "," +"COUNTY" + "," + "ST" + "," + "MAJO" + "," + "RESV CAT" + "," + "DISCOUNT RATE"
+ "," + "NET OIL INTEREST" + "," + "NET GAS INTEREST" + "," + " WORKING INTEREST" + "," + "GROSS WELLS" + "," + "ULT OIL" + "," + "ULT GAS" + "," + "GROSS OIL" + ","
+ "GROSS NGL" + "," + "GROSS GAS" + "," + "NET OIL" + "," + "NET GAS" + "," + "NET NGL" + "," +"REVENUE TO INT." + "," + "OPER. EXPENSE" + "," + "TOT INVEST." + ","
+ "REVENUE OIL" + "," + "REVNUE GAS" + "," + "OPERATING PROFIT" + "," + "REVENUE NGL" + "," + "DISC NET INCOME" + "," + "SEQ" + "," + "WELL ID" + "," + "INC ASN" + ","
+ "LIFE YEARS" + "," + "OWN QUAL" + "," + "PRODUCTION TAX" + "," + "AD VALOREM TAX");
output.WriteLine();
output.WriteLine();
String[] partsComb = list.ToArray(); // string array that takes in the list
Array.Sort(partsComb);
CsvFileDescription outputFileDescription = new CsvFileDescription
{
SeparatorChar = '\t',
FirstLineHasColumnNames = false,
};
CsvContext cc = new CsvContext();
cc.Write(partsComb ,output, outputFileDescription);
I'm just trying to get this up and running to output it correctly to a CSV file. Any help would be greatly appreciated.

Your code doesn't appear to be using any of the features of Linq2Csv.
You get the error because you're just trying to write a string out which doesn't have csvcolumn attribute.
Why do you think you need linq2csv? From your code you read in 2 files sort the lines from those files then try to write the result back out. You're not using any of Linq2csv's features. You could just write this result straight to a file & not use linq2csv.
Alternatively, create a class that matches the data you are reading, then follow the instructions in the article to read the file into a list of that class. merge & write back out again using linq2csv.
More Info
This line from the article reads the data in
IEnumerable<Product> products = cc.Read<Product>("products.csv", inputFileDescription);
You need to do this for each file you want to read into 2 lists eg parts & parts2 from your code.
having done this, follow the example for writing a file, but pass parts.union(parts2) instead of products2.
cc.Write(products2, "products2.csv", outputFileDescription);

Related

C# Deserialize lists within a .dat file to a text box

I have created an application that will save lists to a .dat file using a binary formatter and serializing the list.
I wish to then de serialize this list and display this within a text box.
Furthermore, I have tried using a for each loop to get every object from the list, but it won't continue through the rest of the lists and stops at the first list stored within the file.
I have been tasked with binary formatter even though Ive been informed its obsolete.
`public InPerson(int iId, string sDate, string sTime, string sDuration, string sPatientname, string
sPhonenumber, string sDoctorid, string sRoomnumber, string sNurseid)
{
this.iId = iId;
this.sDate = sDate;
this.sTime = sTime;
this.sDuration = sDuration;
this.sPatientname = sPatientname;
this.sPhonenumber = sPhonenumber;
this.sDoctorid = sDoctorid;
this.sRoomnumber = sRoomnumber;
this.sNurseid = sNurseid;
}
//To String method for saving
public override string ToString()
{
return "In Person Apppointment: " + iId + System.Environment.NewLine +
"Date: " + sDate + System.Environment.NewLine +
"Time: " + sTime + System.Environment.NewLine +
"Duration: " + sDuration + System.Environment.NewLine +
"Patients Name: " + sPatientname + System.Environment.NewLine + "Patients Number: " + sPhonenumber + System.Environment.NewLine +
"Doctors ID: " + sDoctorid + System.Environment.NewLine +
"Room Number: " + sRoomnumber + System.Environment.NewLine +
"Nurse id: " + sNurseid + System.Environment.NewLine + "";
}
InPerson NewInPersonApp = new InPerson(Convert.ToInt32(txtID.Text), dateTimePickerBooking.Text, txtTime.Text, txtDuration.Text, txtPatientName.Text, txtPhoneNumber.Text, txtDoctorID.Text, txtRoomAllocated.Text, txtNurseID.Text);
List<InPerson> InPersonList = new List<InPerson>();
InPersonList.Add(NewInPersonApp);
const String filename = "appointments.dat";
FileStream outFile;
BinaryFormatter bFormatter = new BinaryFormatter();
outFile = new FileStream(filename, FileMode.Append, FileAccess.Write);
bFormatter.Serialize(outFile, InPersonList);
outFile.Close();`
`
I wish to use this code to loop every list out from the file.
`InPersonList = (List<InPerson>)bFormatter.Deserialize(inFile);
foreach (InPerson a in InPersonList)
{
txtBookings.Text += a.ToString();
}`

How to write to a continues line in CSV file while maintaining more then one line of code

I am trying to write a continues line in CSV.
Using one line of code it would look like that:
outputFile.WriteLine("1111" + "," + "2222" + "," + "3333" + "," + "4444" + "," + "5555" + "," + "6666");
well the line is too long for me and I want to split it into two or more lines of code.
I have tried this:
outputFile.WriteLine("1111" + "," + "2222" + "," + "3333" + "," + "4444");
outputFile.WriteLine("," + "5555" + "," + "6666");
But the end resulte is two lines in the CSV file with an empty cell in the second line.
You can use StringBuilder like this:
StringBuilder line = new StringBuilder();
line.Append("1111");
line.Append(",");
line.Append("2222");
//..
outputFile.WriteLine(line.ToString());

C# Append text with Encoding.UTF8

I have this code:
using (var sw = new StreamWriter(path + kat + "/" + namec, false, Encoding.UTF8))
{
sw.WriteLine(namex + "," + address + "," + web + "," + email + "," + phone + "," + linksx + "," + transport);
}
How I can append text and include Encoding.UTF8 ?
I tried this:
using (StreamWriter sw = File.AppendText(path + kat + "/" + namec, false, Encoding.UTF8))
But i got this:
Severity Code Description Project File Line Suppression State
Error CS1501 No overload for method 'AppendText' takes 3
arguments visitdenmark C:\Users\???\Documents\Visual Studio
2015\Projects\visitdenmark\visitdenmark\Form1.cs 193 Active
Actually the error message is correct. Claiming that AppendText does not take 3 arguments.
But in my optinion there is no need to leave your first approach with the StreamWriter aside. But in order to append the text you should change the second parameter to true
using (var sw = new StreamWriter(path + kat + "/" + namec, true, Encoding.UTF8))
{
sw.WriteLine(namex + "," + address + "," + web + "," + email + "," + phone + "," + linksx + "," + transport);
}

Regular expression getting html between two comments

I am trying to get a snippet of HTML between to comments.
I will need to parse the HTML between the start/end later.
I am actually reading from an html file but for test purposes I mocked the following up:
string emailFeedTxtStart = "<!--FEED FOR RECEIPT GOES HERE-->";
string emailFeedTxtEnd = "<!--FEED FOR RECEIPT ENDS HERE-->";
string html =
emailFeedTxtStart + Environment.NewLine +
#"<td align=""center"">" + Environment.NewLine +
#"<table style=""table-layout:fixed;width:380px"" border=""0"" cellspacing=""0"" cellpadding=""0"">" + Environment.NewLine +
"<tbody>" + Environment.NewLine +
"<tr>" + Environment.NewLine +
"<td>" + Environment.NewLine +
"</td>" + Environment.NewLine +
"</tr>" + Environment.NewLine +
"</tbody>" + Environment.NewLine +
"</table>" + Environment.NewLine +
"</td>" + Environment.NewLine +
emailFeedTxtEnd;
string patternstart = Regex.Escape(emailFeedTxtStart);
string patternend = Regex.Escape(emailFeedTxtEnd);
string regexexpr = patternstart + #"(.*?)" + patternend;
//string regexexpr = #"(?<=" + patternstart + ")(.*?)(?=" + patternend + ")";
MatchCollection matches = Regex.Matches(#html, #regexexpr);
matches returned is 0.
(note there is a lot more HTML between the ).
Any help would be greatly appreciated.
What are you going to parse the HTML with after? Because there's probably a way you can just do away with actually manipulating the HTML string beforehand. Here's a solution anyway:
string afterFirst = html.Substring(Regex.Match(html, emailFeedTxtStart).Index + emailFeedTxtStart.Length);
string between = afterFirst.Substring(0, Regex.Match(afterFirst, emailFeedTxtEnd).Index);

Properly formatted text output to .txt file

I'am exporting some data to a .txt file as follows:
String content;
String path=#"e:\coding\";
String name="test.txt";
path+=name;
System.IO.File.Delete(path);
for (i=0;i<row-1;i++)
{
try
{
if (r[i].points.Count() > 2)
{
content = "Route " + (i + 1).ToString() +" Truck_id:"+trk[i].truck_name.ToString()+ " Max_load="+trk[i].capacity.ToString()+ "\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine);
System.IO.File.AppendAllText(path, "Points Load Reached_AT Max_load" + Environment.NewLine);
System.IO.File.AppendAllText(path, "========================================" + Environment.NewLine);
for (int j = 0; j < (r[i].points.Count()); j++)
{
content = r[i].points[j].ToString() + " " + c[r[i].points[j]].load.ToString() +" "+ r[i].time_list[j].ToString()+" "+c[r[i].points[j]].max_load.ToString()+"\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine);
}
content = "Total " + r[i].ld.ToString() + "\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine );
content = "Route Complete: " + r[i].reach_at.ToString();
System.IO.File.AppendAllText(path, content + Environment.NewLine+Environment.NewLine);
}
}
catch (IndexOutOfRangeException e)
{
break;
}
}
As expected the output I get is not properly formatted:
The spaces are causing the text to be jumbled and not arranged. My reputation does'nt allow me to post a screenshot but I guess It can be understood what is happening.
Is there way so that the text is properly formatted neatly column wise without looking jumbled.
If you need a text, you can use tabs:
System.IO.File.AppendAllText(path, "Points\t\tLoad\t\tReached_AT\t\tMax_load" + Environment.NewLine);
// ...
content = r[i].points[j].ToString() + "\t\t " + c[r[i].points[j]].load.ToString() +"\t\t"+ r[i].time_list[j].ToString()+"\t\t"+c[r[i].points[j]].max_load.ToString()+"\n";
Just play with amount of tabs (\t for one, \t\t for two, etc...). Hope it can help.
Another solution would be to use commas:
System.IO.File.AppendAllText(path, "Points,Load,Reached_AT,Max_load" + Environment.NewLine);
and save to CSV-file (comma-separated values). Then you can import the data to Microsoft Excel or to other software.
You can find bunch full of good information on how to format the string contents in the The format item MSDN but for quick answer, an example for your string
content = "Route " + (i + 1).ToString() + " Truck_id:" + trk[i].truck_name.ToString() + " Max_load=" + trk[i].capacity.ToString() + "\n";
If we assume,
i maximum 10 digits,
Truck_name max 45 characters
capacity max 10 digits
content = String.Format("{0,-20}{1,55}{2,20} " + Environment.NewLine, "Route " + (i + 1).ToString(), " Truck_id:" + trk[i].truck_name.ToString(), " Max_load=" + trk[i].capacity.ToString());

Categories