0

I want to write data to a csv file. But i can only get to the next row, not to the next column. I hope some people here know how to get to the next column.

String fileName = "C:\\Users\\hogen\\Desktop\\test.csv";
FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
string columnTitles = "test, test \n test \n test";
fileStream.Write(Encoding.ASCII.GetBytes(columnTitles), 0, columnTitles.Length);
fileStream.Close();

I get now:

test, test
test
test

in the csv file. How do i get the second test of the first row in the next column?

Maybe if u guys know this, could maybe give some good examples of reading columns with filestream?

haldo
  • 14,512
  • 5
  • 46
  • 52
  • You can try to find a lot of examples in this thread: https://stackoverflow.com/questions/2081418/parsing-csv-files-in-c-with-header – Roman Patutin Jun 27 '19 at 14:42
  • I tried, but have no clue whats happening there, and i would like to understand what is actually happen. Or at least keep it really really simple. – Nick Hogenkamp Jun 27 '19 at 14:52
  • Firstly why do you want to do it with a basic filestream? Why not use a ready-made CSV library? There are many choices you could make use of. is this a learning exercise to implement your own CSV interface? – ADyson Jun 27 '19 at 15:06
  • CSV stands for comma separated values. You need to add a comma between each field's value. e,.g. "Field1, Field2, Field3" for the header row then "Value1, Value2, Value3" for a data row. – T_Bacon Jun 27 '19 at 15:18

2 Answers2

0

I think you're asking how to skip a column?

If you want a blank column, just add another comma: test,,test - make sure there are no spaces or other characters between the two commas.

ADyson
  • 57,178
  • 14
  • 51
  • 63
-1

No it doesn't seperate..

I found also this tutorial:

String fileName = "C:\\Users\\hogen\\Desktop\\test1.csv";
StringBuilder content = new StringBuilder();
content.AppendLine("name, age");
content.AppendLine("nick, 26");
File.AppendAllText(fileName, content.ToString());

Output: https://i.stack.imgur.com/AWxMG.png

  • sometimes if you open in Excel you have to import it via the text import tool, not just open it directly. But first, try opening the file in Notepad to check it looks like a valid CSV. Creating a valid CSV and opening it correctly in Excel are two separate issues. – ADyson Jun 27 '19 at 16:40
  • BTW I created a blank console application, ran your code above, and it created a valid CSV file (I checked via Notepad), and the CSV also opened correctly and automatically in Excel (2010) just by double-clicking on it in Explorer. So, I don't know how you tried to open it, but it doesn't seem to be a problem related to the C# code. – ADyson Jun 27 '19 at 16:46
  • P.P.S. if you're complaining about still having a problem, then that is not an "answer" to your question. This code should be added to your original question (using the "edit" button) – ADyson Jun 27 '19 at 16:46