从.txt中读取的行中获取特定单词

时间:2016-04-13 08:21:56

标签: c# .net wpf streamreader

现在我正在读取.txt中的一些行。 让我们说,用户输入他的名字并在.txt中保存"登录{用户名} 2016年4月13日上午10:55"。 (只是一个例子。)

现在我想阅读.txt并将特定部分打印到文本框中。 意思是,在文本框中显示" {Username} - 2016年4月13日 - 上午10:55"。

到目前为止,我能够从.txt中读取并打印整行。

private void button_print_results_Click(object sender, RoutedEventArgs e)
{
    int counter = 0;
    string actual_line;


    System.IO.StreamReader file_to_read =
    new System.IO.StreamReader("myText.txt");
    while ((actual_line = file_to_read.ReadLine()) != null)
    {

        textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
        counter++;
    }

    file_to_read.Close();
}

有没有办法在没有覆盖整个文件的情况下达到此目的?

不,我无法更改名称等的保存格式。 (我在这里使用它们以便更好地理解,我需要读取/检查的实际行是不同的并且是自动生成的。)

我不希望完整的工作代码,如果你能告诉我我需要查看哪些命令,那就太棒了。自从我上次使用c#/ wpf以来已经有很长一段时间了,我从未在Streamreader上工作太多......

由于

4 个答案:

答案 0 :(得分:1)

您可以拆分actual_line字符串,以便获得一个字符串数组。然后将要在TextBox中显示的字符串填入其中。

string[] values = actual_line.Split(' ');
textBox_results.Text = textBox_results.Text + "\n" + values[2] + " " + values[6] + " " + values[7];

例如,TextBox中的文字为" {username}上午10:55 "

答案 1 :(得分:1)

对此有几种可能的解决方案。对您的案例来说,最直接的方法是使用SubstringReplace

由于较早的string始终为Logged in(请注意最后一个空格),您只想在短语后获取string的休止符,只替换时间词的介词(“on”,“at”)用短划线(“ - ”)你可以利用它:

string str = "Logged in {username} on 13/04/2016 at 10:55 am";
string substr = str.Substring(("Logged in ").Length) //note the last space
                   .Replace(" on ", " - ")
                   .Replace(" at ", " - ");

在您的实施中,这就是它的样子:

while ((actual_line = file_to_read.ReadLine()) != null)
{
    actual_line = actual_line.Substring(("Logged in ").Length) //note the last space
                   .Replace(" on ", " - ")
                   .Replace(" at ", " - ");
    textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
    counter++;
}

(注意:上面的解决方案假设{username} 包含时间词的间隔介词 - 这几乎可能是{username}

答案 2 :(得分:1)

我认为正则表达式是您尝试实现的最佳工具。你可以这样写:

Regex regex = new Regex("Logged in (?<userName>.+) on (?<loginTime>.+)");
while ((actual_line = file_to_read.ReadLine()) != null)
{
    Match match = regex.Match(actual_line);
    if (match.Success) {
        string loginInfo = string.Format("{0} - {1}", match.Groups["userName"], match.Groups["loginTime"]);
        textBox_results.Text = textBox_results.Text +"\n"+ loginInfo;
    }
}

答案 3 :(得分:0)

你可以使用正则表达式获得更好的表现,正如@ Dmitry-Rotay在前面的评论中所建议的那样,但是如果你输入一个不那么大的文件,你的循环+字符串操作是一个可接受的折衷方案。

始终使用Environment.NewLine而不是“\ n”,它更具可移植性。

while ((actual_line = file_to_read.ReadLine()) != null)
{
    actual_line = actual_line
               .Replace(("Logged in "), String.Empty)
               .Replace(" on ", " - ")
               .Replace(" at ", " - ");
    textBox_results.Text = textBox_results.Text 
               + System.Environment.NewLine 
               + actual_line;
    counter++;
}