从文本文件中读取特定单词

问题描述 投票:0回答:3

我想创建一个从文件中读取的C#应用​​程序,查找特定的字符串(单词)。我不知道会怎么样。

我的文件看起来像这样:

hostname: localhost

我怎么读只阅读'localhost'部分?

using (StreamReader sr = File.OpenText(config))
{
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
        string hostname = s;
        Console.WriteLine(hostname);
    }
}

^(up)从文件中读取所有内容。

c# string
3个回答
1
投票

根据你的代码,你将文件内容存储在string hostname中,所以现在你可以拆分你的hostnamelike: String[] byParts = hostname.split(':')

byPart[1] will contain 'locahost' <br/>
byPart[0] will contain 'hostname'<br/>

或者,如果您有情况,您将始终使用hostname: localhost获取文件,那么您可以使用: hostname.Contains("localhost")

接下来,您可以使用if()来比较您的逻辑部分。

希望能帮助到你。


0
投票
using (var sr = File.OpenText(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("localhost"))
        {
            Console.WriteLine(line);
        }
    }
}

这将逐行读取文件,如果该行包含localhost,它将把该行写入控制台。这当然会经历所有的线路,你可能想要在找到线路后打破或做其他事情。或不,取决于您的要求。


0
投票

这是未经测试的!

以下代码段利用了Regex的捕获组功能。它将在当前行中寻找完全匹配。如果匹配成功,它将打印出捕获的值。

// Define regex matching your requirement
Regex g = new Regex(@"hostname:\s+(\.+?)"); // Matches "hostname:<whitespaces>SOMETEXT" 
                                            // Capturing SOMETEXT as the first group
using (var sr = File.OpenText(path))
{
    string line;
    while ((line = sr.ReadLine()) != null) // Read line by line
    {
        Match m = g.Match(line);
        if (m.Success)
        {
            // Get value of first capture group in regex
            string v = m.Groups[1].Value;
            // Print Captured value , 
            // (interpolated string format $"{var}" is available in C# 6 and higher)
            Console.WriteLine($"hostname is {v}"); 
            break; // exit loop if value has been found
                   // this makes only sense if there is only one instance
                   // of that line expected in the file.
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.