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);
}
Related
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();
}`
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());
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);
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);
I'm trying to update a file via the GitHub API.
I've got everything setup, and in the end the actual file is updated, which is a good thing.
However, let's say I've got these 2 files in my repo
FileToBeUpdated.txt
README.md
And then I run my program
The FileToBeUpdated.txt is updated, like it should, however the README.md is deleted.
This is the code with the 5 steps to update the file:
private static void Main()
{
string shaForLatestCommit = GetSHAForLatestCommit();
string shaBaseTree = GetShaBaseTree(shaForLatestCommit);
string shaNewTree = CreateTree(shaBaseTree);
string shaNewCommit = CreateCommit(shaForLatestCommit, shaNewTree);
SetHeadPointer(shaNewCommit);
}
private static void SetHeadPointer(string shaNewCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"sha\":" + "\"" + shaNewCommit + "\", " +
// "\"force\":" + "\"true\"" +
"}";
// TODO validate ?
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "refs/heads/master", "PATCH", contents);
}
private static string CreateCommit(string latestCommit, string shaNewTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"parents\" :[ \"" + latestCommit + "\" ], " +
"\"tree\":" + "\"" + shaNewTree + "\", " +
"\"message\":" + "\"test\", " +
"\"author\": { \"name\": \""+ Constants.Username +"\", \"email\": \""+ Constants.Email+"\",\"date\": \"" + DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "\"}" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "commits", contents);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.sha;
}
private static string CreateTree(string shaBaseTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"tree\" :" +
"[ {" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "trees", contents);
var foo = JsonConvert.DeserializeObject<TreeRootObject>(downloadString);
return foo.sha;
}
private static string GetShaBaseTree(string latestCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "commits/" + latestCommit);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.tree.sha;
}
private static string GetSHAForLatestCommit()
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "refs/heads/master");
var foo = JsonConvert.DeserializeObject<HeadRootObject>(downloadString);
return foo.#object.sha;
}
private static WebClient GetMeAFreshWebClient()
{
var webClient = new WebClient();
webClient.Headers.Add(string.Format("Authorization: token {0}", Constants.OAuthToken));
return webClient;
}
Which part am I missing? Am I using the wrong tree to start from?
It seems that in the function CreateTree I should set the base_tree at the root level, not at the level of each tree I create.
So in the function CreateTree the contents become this:
string contents = "{" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," + // IT'S THIS LINE!
"\"tree\" :" +
"[ {" +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
Updated GitHub documentation: https://github.com/Snakiej/developer.github.com/commit/2c4f93003703f68c4c8a436df8cf18e615e293c7