I am writing an console application which writes to a text file.
I have written the code but my output doesn't give me what I need.
The output I get is as follows:
KCooke409155874935sa975891/1/2013
and it should be like this:
KCooke 409155874935 sa 97589 1/1/2013
The code I have is as follows:
foreach (var account in sortedAccounts)
{
var outputLine =
account.accountholder +
account.accountnumber +
account.accounttype.Substring(0, 2) +
account.amount +
account.date.ToShortDateString();
//output
File.WriteAllText(text, outputLine);
}
is it possible to split by a tab. I tried using .Split() but I get errors.
Thank you
You don't need splitting here, you are looking for join
string.Join("\t", account.accountholder,
account.accountnumber,
account.accounttype.Substring(0, 2),
account.amount,
account.date.ToShortDateString());
Adding the tab character should so what you need
foreach (var account in sortedAccounts)
{
var outputLine =
account.accountholder + "\t" +
account.accountnumber + "\t" +
account.accounttype.Substring(0, 2) + "\t" +
account.amount + "\t" +
account.date.ToShortDateString();
//output
File.WriteAllText(text, outputLine);
}
Insert a Tab character '\t' like this:
var outputLine = account.accountholder + "\t" +
account.accountnumber + "\t" +
...
Try this:
foreach (var account in sortedAccounts)
{
var outputLine = string.Format("{0}\t{1}\t{2}\t{3}\t{4}",
stringaccount.accountholder,
account.accountnumber,
account.accounttype.Substring(0, 2),
account.amount,
account.date.ToShortDateString());
//output
File.WriteAllText(text, outputLine);
}
You haven't actually included a tab character in your string...
var outputLine =
account.accountholder + "\t" +
account.accountnumber + "\t" +
account.accounttype.Substring(0, 2) + "\t" +
account.amount + "\t" +
account.date.ToShortDateString();
Related
Having trouble figuring out how to prevent the last key in my array to not have a comma. Since its being exported to a .Json file the last key shouldn't have a ",".
I know you can detect it by using .Last();, but I can't seem to make that work. Any recommendations?
//Data Path
string dataPath = #"..\..\FileIOExtraFiles\DataFieldsLayout.txt";
string[] dataList = File.ReadAllLines(dataPath);
//save Data data
using (StreamWriter outStream = new StreamWriter(outputFolder + #"\CharacterStringData3.json"))
{
outStream.WriteLine("{");
for (int i = 0; i < dataFile.Length; i++)
{
string s = dataFile[i];
char last = s.Last();
if (s == "")
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
}
else
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\",");
}
}
outStream.WriteLine("}");
}
Output:
{
"data1":"item1",
"data2":item2",
"lastKey":item3",//trying to remove comma from last key in array.
}
As others have pointed out, it doesn't make sense that you are building json manually, but given that this is a question more about technique, here is one approach: you could change it to this:
var commaSuffix = (i == dataFile.Length - 1) ? "," : string.Empty;
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\"" + commaSuffix);
The suffix would be used on every iteration except the last.
Change this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
To this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \""+(i==dataFile.Length?",":""));
Instead of using outStream.WriteLine() at every step, store it in a string. Then you can remove the last comma from that string and write the whole string at once:
//Get last index of comma
int lastCommaIndex = outputString.LastIndexOf(',');
//Create new StringBuilder with everything before the last comma
StringBuilder sb = new StringBuilder(outputString.Substring(0,lastCommaIndex));
//Add everything after the last comma, or just add a closing brace
//sb.Append("}"); //This instead of next line
sb.Append(outputString.Substring(lastCommaIndex+1));
//Add contents of StringBuilder to the Stream
outSteam.WriteLine(sb);
Help me please write every value to different cell, I try to write data in the CSV file but when I open this file in Excel the value showing in one line (cell). Did different various separators between the values "." and ",". But the results in Office 2010 and 2012 the same... And one more interesting think, in Office 2007 that work's with (*.xls)...
string s = "";
s += "Nick-Name, Category, Web-Pages, ICQ, Skype, Mail, Phone\r";
for (int i = 0; i < listOfUsers.Count; i+=3)
{
s += nickName[i] + "," + category[i] + "," + webList[i] + "," + ICQList[i] + "," + skypeList[i] + "," + mailList[i] + "," + phoneList[i] + ";\r";
}
System.IO.File.WriteAllText(#"" + folder + "Parse_people_list.csv", s, System.Text.Encoding.UTF8);
(source: pixs.ru)
(source: pixs.ru)
Try delimiting with tabs instead - Excel handles tab-delimited data better than comma-delimited since commas within the data may cause issues.
You can also use StringBuilder.AppendLine to improve performance and avoid adding line breaks manually:
StringBuilder s = new StringBuilder();
s.AppendLine("Nick-Name\tCategory\tWeb-Pages\tICQ\tSkype\tMail\tPhone");
for (int i = 0; i < listOfUsers.Count; i+=3)
{
s.AppendLine(
nickName[i] + "\t"
+ category[i] + "\t"
+ webList[i] + "\t"
+ ICQList[i] + "\t"
+ skypeList[i] + "\t"
+ mailList[i] + "\t"
+ phoneList[i]);;
}
I am reading a text file and picking out certain keywords and adding strings to them and then writing it to another empty text document. My problem is that since I am doing this to multiple strings, it writes the text file multiple times over and I end up with 5 additional lines for every line in the original text document. Anyone know another method that I could use to get this done?
var fileContents = System.IO.File.ReadAllLines(textBox5.Text);
var outFileContents = new List<string>();
foreach (var line in fileContents)
{
if (line.Contains("Start **** Connect Process")) //Text to find
outFileContents.Add(line + "," + Environment.NewLine + "*****" + Environment.NewLine); //Add your text
else
outFileContents.Add(line + ","); //Keep column
if (line.Contains("Start $$$$$$ Connect Process"))
outFileContents.Add(line + "," + Environment.NewLine + "$$$$$$" + Environment.NewLine);
else
outFileContents.Add(line + ",");
if (line.Contains("Fail to send &&&&&&&&"))
outFileContents.Add(line + "," + Environment.NewLine + "&&&&&&" + Environment.NewLine);
else
outFileContents.Add(line + ",");
if (line.Contains("Start ##### Process"))
outFileContents.Add(line + "," + Environment.NewLine + "######" + Environment.NewLine);
else
outFileContents.Add(line + ",");
if (line.Contains("ConnectionStatus: ######"))
outFileContents.Add(line + "," + Environment.NewLine + "######" + Environment.NewLine);
else
outFileContents.Add(line + ",");
System.IO.File.WriteAllLines(textBox6.Text, outFileContents);
}
Process.Start(textBox6.Text);
}
The problem isn't because you're calling WriteAllLines in a loop. WriteAllLines overwrites the file. Just see the documentation.
The problem is that you're adding every line to the output list five times.
What you have is essentially:
for every line
if ()
add modified line
else
add unmodified line
if ()
add modified line
else
add unmodified line
Five of those conditionals means five copies of the line being added to the output list.
You need to build your string in a temporary buffer and add it to the list just once. Something like:
for(...)
{
StringBuilder sb = new StringBuilder(line);
if (line.Contains("Start **** Connect Process"))
sb.Append("," + Environment.NewLine + "*****" + Environment.NewLine);
else
sb.Append(',');
// do that for each of your conditionals.
// and finally, add the line to the output buffer:
outFileContents.Add(sb.ToString());
}
Now, you should remove the WriteAllLines out of the loop so that you're not rewriting the file every time. So your code becomes:
for (....)
{
// do stuff
}
File.WriteAllLines(...)
get this System.IO.File.WriteAllLines(textBox6.Text, outFileContents); out of foreach
var fileContents = System.IO.File.ReadAllLines(textBox5.Text);
var outFileContents = new List<string>();
foreach (var line in fileContents)
{
}
System.IO.File.WriteAllLines(textBox6.Text, outFileContents);
Process.Start(textBox6.Text);
}
The reason is because you're writing the text over and over (it's in a loop). Instead you need to write to the file just once at the end of your operation by moving the WriteAllLines method call.
Additionally you might want to think about using the StringBuilder class for generating your contents.
var fileContents = System.IO.File.ReadAllLines(textBox5.Text);
var outFileContents = new List<string>();
foreach (var line in fileContents)
{
if (line.Contains("Start **** Connect Process")) //Text to find
outFileContents.Add(line + "," + Environment.NewLine + "*****" + Environment.NewLine); //Add your text
else
outFileContents.Add(line + ","); //Keep column
if (line.Contains("Start $$$$$$ Connect Process"))
outFileContents.Add(line + "," + Environment.NewLine + "$$$$$$" + Environment.NewLine);
else
outFileContents.Add(line + ",");
if (line.Contains("Fail to send &&&&&&&&"))
outFileContents.Add(line + "," + Environment.NewLine + "&&&&&&" + Environment.NewLine);
else
outFileContents.Add(line + ",");
if (line.Contains("Start ##### Process"))
outFileContents.Add(line + "," + Environment.NewLine + "######" + Environment.NewLine);
else
outFileContents.Add(line + ",");
if (line.Contains("ConnectionStatus: ######"))
outFileContents.Add(line + "," + Environment.NewLine + "######" + Environment.NewLine);
else
outFileContents.Add(line + ",");
}
System.IO.File.WriteAllLines(textBox6.Text, outFileContents);
Process.Start(textBox6.Text);
I am trying to output to a text file, with the following C# code. The problem is that my outputted information has a comma at the end of it and this won't work with the program that uses the file after. I'm trying to figure out how to get rid of this comma...
var toFile = Path.Combine(GetTextPath(),
string.Format(heatname + "_{0}.txt", DateTime.Now.ToString("yyyyMMdd")));
string ElementsNum = RoundedValues.Count.ToString();
DateTime dt = System.DateTime.Now;
var year = dt.ToString("yy");
var month = dt.ToString("MM");
var day = dt.ToString("dd");
var minute = dt.ToString("mm");
using (var fs = File.OpenWrite(toFile))
using (TextWriter sw = new StreamWriter(fs))
{
sw.Write("NA" + "," + dt.Hour.ToString() + "," + minute + "," + day + ","
+ month + "," + year + "," + "ALTEST " + "," +
"ALTEST " + "," + heatgrade + " " + "," + " " + "," + heatname + "," +
DT2.Rows[0][3].ToString() + "," + heatgrade + "," + "OE2" + "," + "," +
"," + "," + "," + "," + "," + " " + ElementsNum);
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
}
}
You can use TrimEnd, for example:
var theString = "abcd,";
var trimmedString = theString.TrimEnd(new[]{','});
In your case, if I'm not mistaken, this is where you want it to happen:
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
If so, you can do this:
var pairs = pair.B.ToString() + ", " + pair.A.ToString() + ",";
sw.Write(pairs.Trim().TrimEnd(new[]{','}));
Here is a linqy way to do it. This would use the Aggregate function of linq.
var x = RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b })
.Aggregate("", (old, item) => {
return old + (old == "" ? "" : ", ") +
item.B.ToSTring() + ", " + item.A.ToString();
});
sw.Write(x);
Version two (go go join!) uses linq to make a array of strings containing the pairs and then combine those pairs seperated by a comma using join.
string [] x = RoundedValues.Zip(Elements,
(a, b) => b.ToSTring() + ", " + a.ToString() ).ToArray();
sw.Write(String.Join(", ",x));
It might be that the following would work, but I'm not where I can test it ... this sure looks sexy (mostly because it is one line and everyone loves one line solutions):
sw.Write(String.Join(", ",
RoundedValues.Zip(Elements,
(a, b) => b.ToSTring() + ", " + a.ToString() )
));
Which would replace
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
}
Another option is to use the StringBuilder.
...
StringBuilder sb = new StringBuilder();
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sb.AppendFormat("{0}, {1},", pair.B, pair.A);
}
sw.Write(sb.ToString().TrimEnd(new[] { ' ', ',' });
I have the following bits of code:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strMovie, strGenre, tmpGenre = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
string strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
catalog.WriteLine(strHeader);
foreach (Movie m in mList)
{
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">" : " <tr id=\"even\" style=\"page-break-inside:avoid\">";
catalog.WriteLine(strMovie);
foreach (string genre in m.Genres)
tmpGenre += ", " + genre;
try
{ strGenre = tmpGenre.Substring(2); }
catch (Exception)
{ strGenre = null; }
strMovie = " <td>\r\n" + " <img src=\".\\images\\" + m.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Certification + " " + m.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
catalog.WriteLine(strMovie);
lineID = lineID == 0 ? 1 : 0;
}
catalog.WriteLine(" </table>\r\n" + " </body>\r\n" + "</html>");
catalog.Close();
}
public static void WritePDF(string cFile, string pdfFile)
{
// Sets up PDF to write to
EO.Pdf.HtmlToPdf.Options.PageSize = new SizeF(8.5f, 11f);
EO.Pdf.HtmlToPdf.Options.OutputArea = new RectangleF(0.5f, .25f, 7.5f, 10.25f);
HtmlToPdf.ConvertUrl(cFile, pdfFile);
}
My HTML file writes fine, but when it tried to convert the HTML file to PDF I get an exception that it times out.
I did a test previously, and had it convert the code (not the file) within the WriteHTML function and it worked great. I have confirmed that the cFile exists and is a valid file (created previously in WriteHTML). The path to pdfFile is valid, and the documentation does not state the file needs to already exist (.ConvertHTML did not need an existing file).
Only thing I can think of is that the catalog.html file isn't released and ready to read yet. I made sure I closed it in the WriteHTML function. How can I test that the file is ready to be read?
Tried setting .MaxLoadWaitTime = 120000 with no luck.
Any clues would be greatly appreciated!
After a battery of further testing, and scouring the EO support forums, it appears to be a limitation of the free version of EO. It seems to have difficulty with HTML files over 3MB.
It's a shame since the EO product is very good, but not unfortunately not worth $250 IMO.