kohhworlwide kohhworlwide - 3 years ago 180
C# Question

TXT into filtered CSV

I'm building a small application that intends to simplify the information displayed in a .txt file and display in Excel (.CSV).

I've already got the information to a String and I'm planning to use the CSVExport library available in Nugget to build the excel file. The thing is that I need to filter and treat the information.
The data has the following format:

0001. 001.0001. 01. 3. 17. 07. 13. 12. 02.0002.V TT. .MTC1.

I intend to isolate the first line (Header), keep its values, formulate a cell called "Controller" -> "MTC1" , Date of the first collect " 13.07.2017 - 14.00h", "Type" -> " TT"

For the rest of the information, I intend to put each data "75","39","00"... in a cell for every 5 minutes after the first collect, per cell.

Controller MTC1

Type TT

Start 20/10/2016 15:45

20/10/2016 15:45 52
15:50 50
15:55 00
16:00 00


My issue is the method that I'm going to use to filtrate the information.
I've been researching some methods to do so but due to my lack of experience I just can't seem to chose the right one. Build a list, StringBuffer...

Here's what I've done up to now:

namespace WindowsFormsApplication1
public partial class Form1 : Form
public Form1()

private void button1_Click(object sender, EventArgs e)
CsvExport myExport = new CsvExport();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
int first=0;
String line = "";
string[] Results = new string[500];
String filepath = openFileDialog1.FileName;
StreamReader sr = new StreamReader(filepath);
int i = 0;
while ((line = sr.ReadLine()) != null)
Results[i] += line;

string csvpath = "C:\\counts.csv";


Now, having this format of file, how would you filter the values for the table?


Answer Source

I think you should take a look at Split method (msdn docs). You can use it like this:

var sr = new StreamReader(filepath);
string[] header = null;
while (true)
    var line = sr.ReadLine();
    if (line == null)
        break; // End of file

    var lineParts = line.Split(" .".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    if (header == null)
        // save first line
        header = lineParts;
        // now header[13] is equal "MTC1"
        // process other lines by one

StringBuilder is helpful if you need to build a string in memory. In your case it's seems that you rather need a StreamWriter object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download