Search code examples
c#asp.netstreamreader

Read a specific thing in a line of a textbox and put in in a windowsform


I have that text file with a few lines of text. In each line there are three necessary pieces of information: Username, Date and Time.

I added the lines to a ListBox control via a StreamReader, and above that control there is a TextBox control. I want to put the username in the TextBox, but I have no idea how.

Here is the code:

namespace Zeiterfassung
{
    public partial class Uebersicht : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sPath = @"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Kommt.txt";

            using (StreamReader sr = new StreamReader(sPath))
            {
                while(!sr.EndOfStream)
                {
                    lb_Kommt.Items.Add(sr.ReadLine());
                }
            }
        }
    }
}

And the lines in the txt-file are all similar to this:

User: KIV\vischer, Datum: 10.09.2018, Zeit: 10:49

I need to put "KIV\Vischer" in the TestBox, not in the ListBox.


Solution

  • I would use a RegEx.

    It could look like this:

    User: (?<user>[^,]*?), Datum: (?<datum>[\d]{1,2}\.[\d]{1,2}\.[\d]{2,4}), Zeit: (?<zeit>[\d]{1,2}:[\d]{2})
    

    You can find more details (and a live demo) here:

    https://regex101.com/r/1YaMxz/2

    Access the values:

    var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
    
    foreach (Match match in matches)
    {
        username = match.Groups["user"].Value;
    }