Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从文本文件中读取特定单词_C#_String - Fatal编程技术网

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

C# 从文本文件中读取特定单词,c#,string,C#,String,我想制作一个C#应用程序,从文件中读取数据,查找特定的字符串(word)。我不知道会发生什么 我的文件如下所示: hostname: localhost 如何仅读取“localhost”部分 using (StreamReader sr = File.OpenText(config)) { string s = ""; while ((s = sr.ReadLine()) != null) { string hostname = s; C

我想制作一个C#应用程序,从文件中读取数据,查找特定的字符串(word)。我不知道会发生什么

我的文件如下所示:

hostname: localhost
如何仅读取“localhost”部分

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

^(向上)读取文件中的所有内容。

根据您的代码,您正在将文件内容存储在
字符串hostname
中,因此现在您可以像这样拆分
主机名:

String[]byParts=hostname.split(“:”)


byPart[1] will contain 'locahost' <br/>
byPart[0] will contain 'hostname'<br/>
byPart[1]将包含“locahost”
byPart[0]将包含“主机名”

或者,如果您遇到这样的情况,即您将始终获得具有
主机名:localhost
的文件,那么您可以使用:

hostname.Contains(“localhost”)


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

希望能有帮助

using (var sr = File.OpenText(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("localhost"))
        {
            Console.WriteLine(line);
        }
    }
}
这将逐行读取文件,如果该行包含localhost,则会将该行写入控制台。这当然会通过所有的线,你可能想打破或做其他事情后,你找到了线。这取决于您的要求。

这是未经测试的

下面的代码段利用了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.
        }
    }
}
//定义符合您需求的正则表达式
Regex g=new Regex(@“主机名:\s+(\.+?)”);//匹配“主机名:SOMETEXT”
//将SOMETEXT捕获为第一组
使用(var sr=File.OpenText(路径))
{
弦线;
while((line=sr.ReadLine())!=null)//逐行读取
{
匹配m=g。匹配(线);
如果(m.成功)
{
//获取正则表达式中第一个捕获组的值
字符串v=m.Groups[1]。值;
//打印捕获的值,
//(插值字符串格式$“{var}”在C#6及更高版本中可用)
WriteLine($“主机名为{v}”);
break;//如果找到值,则退出循环
//这只有在只有一个实例的情况下才有意义
//文件中预期的该行的。
}
}
}

你想达到什么样的目标?您是否正在尝试确定文本文件是否包含单词localhost?或者您正在尝试获取主机名(在本例中为localhost)?如果您正在尝试检查文件是否包含特定单词,请遍历所有行并调用line.contains()。是否考虑使用正则表达式进行匹配和捕获?例如:@spreson我正在尝试获取“localhost”行。@Fang你也能给我举个例子吗?@Luke:如果你还有任何疑问,请随时提问:)谢谢你的回复。但我想你不是很了解我。我正在寻找“localhost”这个词。假设我有一个基于.txt文件的账户;用户名:Luke->我只想要Luke密码:tesd->我只想要'testd'字,因为上面的代码也可以工作。您将在拆分数组中拥有字符串的两个部分<代码>byPart[1]将包含“locahost”,byPart[0]将包含“hostname”
。因此,在给定的示例中,
username:Luke
byPart[0]将包含“username”&byPart[1]将包含“Luke”.更改
String[]byParts=hostname.Split(“:”)
to
string[]byParts=hostname.Split(“:”)和try@mayak还是一样。