I have a loop, which writes the values of an array into a .csv file. It is appending each line, so it writes the values vertically, however, I would like it to write each value in a different column rather than by line, that way I can filter the content after running the program.
My initial thought was to save all the values in one variable and then just write the variable to the .csv file, but I believe this would fill all values into one cell instead of distributing them to different columns.
I need it to write all of the values of the array on each loop, and then move to the next line on the each time it loops if that makes sense.
string pathCleansed = #"myfilename.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision,
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
These are the current results: current results
This is what I would like it to do: desired results
I have had good success with CsvHelper package. You can find more information about it here https://joshclose.github.io/CsvHelper/api/CsvHelper/CsvWriter/.
This helper implements IDisposable so be sure to dispose if it when you're done or wrap it in a using which is more preferred. You will have to provide a writer object to CsvHelper. In the past I've used MemoryStream and StreamWriter.
//Headers if you want
csvWriter.WriteField("StreetAddress1");
csvWriter.WriteField("StreetAddress2");
csvWriter.WriteField("subDivision");
csvWriter.WriteField("City");
csvWriter.WriteField("PostalCode");
csvWriter.WriteField("MainDivision");
csvWriter.WriteField("ConfidenceIndicator");
csvWriter.NextRecord();
//Your Loop Here
{
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].confidenceIndicator);
csvWriter.NextRecord();
}
Update: I was able to get the desired results by changing to code to:
string pathCleansed = #"myfilename.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + "," +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
Related
I'm attempting to read a line from a file (csv header) and create a column list that prepends "c[num]_" in front of each column with this code:
int colCount=0;
string line = "col1,col2,col3,col4,col5";
string ColumnList = "([" + (++colCount).ToString() + "_" + line.Replace(",", "],[c" + (++colCount).ToString() + "_") + "]";
I know it's not elegant, but I'm also not sure why my colCount variable doesn't increment inside the replace?? It results with a string like:
([c0_col1],[c1_col2],[c1_col3],[c1_col4],[c1_col5])
The counter increments the first time and then not again inside the replace. Any insights? I think it might be better written with a Regex ReplaceEvaluator but I haven't been able to piece that together yet either.
The paramter of the Replace method is string, and the expression you've entered there is just a string. The count will always be 2. It's not a Func, it a string.
You can use the following Linq to easily achieve the conversion you'd like:
string ColumnList = string.Join(",", line.Split(',').Select((s, i) => $"[c{i + 1}_{s}]"));
I have a method that copies selected image from an OpenFileDialog to a defined location, and I want to check if an image with the same name exists, and if so to change the name on the fly.
Here is my method:
public void SaveImage(IList<AppConfig> AppConfigs, string ImageNameFilter)
{
string imgPath = AppConfigs[0].ConfigValue.ToString();
Int32 i = 0;
StringBuilder sb = new StringBuilder(selectedFileName);
while (File.Exists(imgPath + "\\" + ImageNameFilter + selectedFileName))
{
sb.Insert(i, 0);
i++;
//ImageNameFilter += (i++).ToString();
}
File.Copy(selectedFile, imgPath + "\\" + ImageNameFilter + selectedFileName);
}
ImageNameFilter is a custom filter that is added at the beginning of each image and the users need this prefix to be able to recognize what the image is used for, only by seeing the prefix. selectedFileName is the name of the image taken with SafeFileName, which means it looks like this - imageName.jpeg.
There are several problems that I have with this code. Firstly, I wanted to change the name like this - imageName1.jpeg, imageName2.jpeg, imageName3.jpeg...imageName14.jpeg.., but if I'm using selectedFileName with the += everything is added, even after the .jpeg, which is not what I want. The only solution that I can think of is to use regex, but I really want to find another way.
Also, incrementing i++ and adding it with += leads to unwanted result which is :
imageName1.jpeg, imageName12.jpeg, imageName123.jpeg...imageName1234567.jpeg.
So, how can I get the result I want and the compromise I see here is to add underscore _ right after the ImageNameFilter and then add i at the beginning of selectedFileName rather in the end as it is by default. But adding something to the beginning of the string is also something I don't know how to do. As you may see I tried StringBuiledr + Insert, but I don't get the expected result.
Basically you need to separate the base file name from the extension (use the helpful methods on Path to do this) before starting the loop, and then keep producing filenames. Each candidate will not be produced based on the last one (it's just based on fixed information and the current iteration count), so you don't need to involve a StringBuilder at all.
Here's one neat way to do it in two steps. First, set up the bookkeeping:
var canonicalFileName = ImageNameFilter + selectedFileName;
var baseFileName = Path.GetFileNameWithoutExtension(canonicalFileName);
var extension = Path.GetExtension(canonicalFileName);
Then do the loop -- here I 'm using LINQ instead of a loop statement because I can, but there's no essential difference from a stock while loop:
var targetFileName = Enumerable.Range(1, int.MaxValue - 1)
.Select(i => Path.Combine(imgPath, baseFileName + i + extension))
.First(file => !File.Exists(file));
File.Copy(selectedFile, targetFileName);
Use Path.GetFileNameWithoutExtension or String.TrimEnd('.') to get the FileName without extension. You can use FileInfo to get the extension as well.
Hi there I have the following code-
richTextBox1.Text = richTextBox1.Text + action + "ok: " + ok.ToString();
richTextBox1.Text = richTextBox1.Text + "err: " + err.ToString();
richTextBox1.Text = richTextBox1.Text + "\r\n";
textBox1.Text = textBox1.Text;
The results look like -
ok:7err:0
But I want-
ok:7
err:0
With spacing, to make it look better how can I do this?
You could add another 2 lines:
richTextBox1.Text += Environment.NewLine;
richTextBox1.Text += Environment.NewLine;
between your "ok" and "err" - assuming you want a blank line between the two lines of output. However, you should either be using string.Format or a StringBuilder to create your output as concatenating strings this way in inefficient.
You also don't need the final:
textBox1.Text = textBox1.Text;
as that is just setting the text box contents back to itself and does nothing.
You've already got your answer, you just have it in the wrong place! The key is to use the escape sequence \r\n, which inserts a carriage return and a new line.
Also, there's no reason to split this code up into multiple lines. You end up incurring a performance penalty for doing so. It's better to do all of the string concatenation at one time. (You aren't doing enough concatenations here to justify using the StringBuilder class, but it's worth keeping in mind that strings are immutable in .NET and writing code accordingly.)
Try rewriting the code like this:
textBox1.Text = textBox1.Text + action + "ok: " + ok.ToString(); + "\r\n" +
"err: " + err.ToString(); + "\r\n";
You can also complete eliminate the last line of code, as that simply sets the value of textBox1.Text to itself. It's a no-op, meaning that it does nothing at all.
first that you could do all these in a single statement, second you could use += operator instead, and third what is that last statement doing?! it not needed, fourth add "\n" after each part you need there is no limit where you should put it, no "\r" needed.
I am currently developing an application in C# where I need to write a tab separated CSV file from the data that it retrieves from a MySQL Database. The database retrieval works fine.
The problem that I am having is writing the file. Between each variable that I am writing I am using the \t which I thought put a tab into the csv, therefore when opening in excel each variable will be in its own cell.
However for some reason it is not doing this it just writes the whole line as one long string. Below is an example of the code that I am code that I have written:
while (reader.Read())
{
int bankID = reader.GetInt16("ban_bankID");
int userID = reader.GetInt16("ban_userID");
string bankUsername = reader.GetString("ban_username");
string accountName = reader.GetString("ban_accountName");
string accountType = reader.GetString("ban_accountType");
decimal overdraft = reader.GetDecimal("ban_overdraft");
char defaultAccount = reader.GetChar("ban_defaultAccount");
string line = bankID + "\t" + userID + "\t" + bankUsername + "\t" + accountName + "\t"
+ accountType + "\t" + overdraft + "\t" + defaultAccount + "\n";
tw.WriteLine(line);
Thanks for your help with this problem.
The format is correct, a CSV expects the file to be COMMA Separated. When saving a Tab delimited file, typically just a txt extension is used (or some people save as .tsv) etc.
If you look at the Save As options in excel the option is Text (Tab Delimited) .txt
If I open the output generated by your sample code (stubbing in the data) everything loads in to Excel 2007 as you would expect.
The problem is your encoding.
You don't show your TextWriter instantiation, but it should look something like this:
TextWriter tw = new Stream(filename, false, Encoding.ASCII);
You should use the Text Import Wizard: Data / From Text. From there you can specify your delimiter to a tab.
A label printer is controled by sending a string of raw ASCII characters (which formats a label). Like this:
string s = "\x02L\r" + "D11\r" + "ySWR\r" + "421100001100096" + date + "\r" + "421100002150096" + time + "\r" + "421100001200160" + price + "\r" + "E\r";
RawPrinterHelper.SendStringToPrinter(printerName, s);
This hardcoded variant works well.
Now I want to put the control string to a .txt file and read it during runtime. Like this:
string printstr;
TextReader tr = new StreamReader("print.txt");
printstr = tr.ReadLine();
tr.Close();
But in this case printer prints nothing.
It seems, that StreamReader adds something else to this string
(If I put the read string to a MessageBox.Show(printstr); everything looks OK. Though, this way we can not see control characters added).
What could be a solution to this problem?
Your code calls tr.ReadLine() once, but it looks like you have multiple lines in that string.
Looks like a Zebra label printer, I've had the displeasure. The first thing you need to fix is the way you generate the print.txt file. You'll need to write one line for each section of the command string that's terminated with \r. For example, your command string should be written like this:
printFile.WriteLine("\x02L");
printFile.WriteLine("D11");
printFile.WriteLine("ySWR");
printFile.WriteLine("421100001100096" + date);
printFile.WriteLine("421100002150096" + time);
printFile.WriteLine("421100001200160" + price);
printFile.WriteLine("E");
printFile.WriteLine();
Now you can use ReadLine() when you read the label from print.txt. You'll need to read multiple lines to get the complete label. I added a blank line at the end, you could use that when you read the file to detect that you got all the lines that creates the label. Don't forget to append "\r" again when you send it to the printer.
It could be that the StreamReader is reading it in an Unicode format. By the way, you are reading in only just one line...you need to iterate the lines instead...Your best bet would be to do it this way:
string printstr;
TextReader tr = new StreamReader("print.txt",System.Text.Encoding.ASCII);
printstr = tr.ReadToEnd();
tr.Close();
Or read it as a binary file and read the whole chunk into a series of bytes instead, error checking is omitted.
System.IO.BinaryReader br = new System.IO.BinaryReader(new StreamReader("print.txt", System.Text.Encoding.ASCII));
byte[] data = br.ReadBytes(br.BaseStream.Length);
br.Close();
Edit:
After rem's comment I thought it best to include this additional snippet here...this follows on from the previous snippet where the variable data is referenced...
string sData = System.Text.Encoding.ASCII.GetString(data);
Hope this helps,
Best regards,
Tom.