首页 > 解决方案 > 在文本框中的一行中读取特定内容并放入 windowsform

问题描述

我有那个带有几行文本的文本文件。每行包含三个必要的信息:用户名、日期和时间。

ListBox我通过 a将线条添加到控件StreamReader,在该控件上方有一个TextBox控件。我想将用户名放在 中TextBox,但我不知道如何。

这是代码:

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());
                }
            }
        }
    }
}

txt 文件中的行都与此类似:

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

我需要将“KIV\Vischer”放在 中TestBox,而不是放在ListBox.

标签: c#asp.netstreamreader

解决方案


我会使用正则表达式。

它可能看起来像这样:

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

您可以在此处找到更多详细信息(和现场演示):

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

访问值:

var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);

foreach (Match match in matches)
{
    username = match.Groups["user"].Value;
}

推荐阅读