Steven Hyslop Steven Hyslop - 1 month ago 7
C# Question

C# how to format readline output

currently, I have read line outputting on rich text box a line from a text file however I want to format that line

if (UsernameCheckers.Text != "Username")
{
string line;

StringBuilder sb = new StringBuilder();

using (System.IO.StreamReader file = new System.IO.StreamReader(@"\\studprint2\PCOUNTER\DATA\REJECT.LOG"))
{
while ((line = file.ReadLine()) != null)
{
if (line.IndexOf(UsernameCheckers.Text, StringComparison.OrdinalIgnoreCase) >= 0)
{
sb.AppendLine(line.ToString() + "\n");
}
}
}
DisplayBox.Text = sb.ToString();
}


an example will be

BCROSS11,Documentname.doc,\STUDPRINT2\computername,15/05/2010,14:48,\1234566788,Insufficient balance,,,/Ts=4BEEA622,107502,10,,

and i want it to say

Username: BCROSS11

File name: Documentname.doc

Error: Insufficient balance

Date: 15/05/2010,14:48

Computer name: \STUDPRINT2\computername


what do i do?

Answer

If the pieces of your string remain at each line in the same order, you can use the String.Split method and slice it in the parts that you need.

Here is a small console application to illustrate the use in your case:

static void Main(string[] args)
{
    string test = @"BCROSS11,Documentname.doc,\STUDPRINT2\computername,15/05/2010,14:48,\1234566788,Insufficient balance,,,/Ts=4BEEA622,107502,10,,";

    // Split the string and it will return an array of strings
    string[] split_array = test.Split(',');

    // Test output to the console
    Console.WriteLine(String.Join("\n", split_array));
    Console.WriteLine("END");

    Console.ReadKey();
}

The output will look like this:

BCROSS11
Documentname.doc
\STUDPRINT2\computername
15/05/2010
14:48
\1234566788
Insufficient balance


/Ts=4BEEA622
107502
10


END

Now you can count the lines and you will know at which position you have to pull out the information. Don't forget that the index starts with 0 and not 1! Note please that a string: ",,," will be split into 3 empty string. This is why in the output you have empty lines.

Comments