Reputation: 43
I have a text file with hundreds of entries formatted like this, I need to display this file on a data grid, or other user friendly control "properly formatted" as per your advise. (my intention is to then export it to excel not an optimal choice though for further processing. all the columns are values in milliseconds so most of times these values are quite big up to 3 hrs, so I need to convert them into hours/minutes/seconds.) What is the best way to approach this task? Can this be done with the StreamReader? Can the conversion take place in code so there is no need to export to excel? Any samples? thank you!
ENTRY DAY ENTRY TIME IN.WORK TEST % TRY CORRER CORTA CICLO MAQUI
O0.TXT
11/07/28 13:39:13 0 0 105 0 0 0 0
O0.TXT
11/07/20 00:00:00 0 0 19145 0 0 0 0
O0.TXT
11/07/19 15:04:10 0 0 32151 0 0 0 0
I want to format it as such:
FILE ENTRY DAY ENTRY TIME IN.WORK TEST % TRY CORRER CORTA CICLO MAQUI
O0.TXT 11/07/28 13:39:13 0 0 105 0 0 0 0
O0.TXT 11/07/20 00:00:00 0 0 19145 0 0 0 0
O0.TXT 11/07/19 15:04:10 0 0 32151 0 0 0 0
O0.TXT 11/07/07 05:22:40 0 0 508 0 0 0 0
I tried using the:
string fileName = "Myfile.txt";
StreamReader sr = new StreamReader(fileName);
string[] delimiter = new string[] { " " };
while (!sr.EndOfStream)
{
string[] lines = sr.ReadLine().Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
........
But I was not able to hold the format I wanted at all, nor to load it into a datagrid etc. for that matter.
Upvotes: 0
Views: 138
Reputation: 16162
string fileName = "Myfile.txt";
string[] delimiter = new string[] { " " };
List<string[]> rows = new List<string[]>();
string[] liens = File.ReadAllLines(fileName);
foreach (string line in liens)
{
rows.Add(line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries));
}
//Now if you want to display them each one row item separated by tab "`\t"` or csv `","`
string separator = "\t";
List<string> output = new List<string>();
foreach (string[] row in rows)
{
output.Add(string.Join(separator, row));
}
string newFile = "result.txt";
File.WriteAllLines(newFile, output.ToArray());//save the output to new file.
Upvotes: 2
Reputation: 948
Is everything fixed? For example, is the date always 6 characters in and 8 characters long (or whatever the case may be)? If so I would split on "\r\n" as opposed to " ", and then process each line individually. You could do:
string fileName = "Myfile.txt";
StreamReader sr = new StreamReader(fileName);
string[] delimiter = new string[] { "\r\n" };
while (!sr.EndOfStream)
{
string[] lines = sr.ReadLine().Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
date = line.Substring(6, 8);
// Do the other processing here.
}
}
Of course, you'll have to come up with some logic for which lines you need to process.
Upvotes: 0