C# 读取文本文件并搜索字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14763109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:55:52  来源:igfitidea点击:

C# read a text file and search for string

c#stringtext

提问by user1570210

In C# how can I open the text file , search for string "mystring" and if string is there then set variable Vara= 1 else Vara= 0 .

在 C# 中,如何打开文本文件,搜索字符串“mystring”,如果存在字符串,则设置变量Vara= 1 否则Vara= 0。

Thanks in advance

提前致谢

采纳答案by Tim Schmelter

Quick & dirty using System.IO.File.ReadAllText:

快速和肮脏的使用System.IO.File.ReadAllText

int Vara = File.ReadAllText(path).Contains("mystring") ? 1 : 0;

回答by Davide Piras

won't do all your exercise to leave you some fun, but here a way to start:

不会做你所有的运动来给你带来一些乐趣,但这里有一个开始:

to get all text of a file into a string variable try this:

要将文件的所有文本放入字符串变量中,请尝试以下操作:

using System.IO;

string fileContent = File.ReadAllText(@"C:\file.txt");

then here to check if your string is inside:

然后在这里检查您的字符串是否在里面:

bool present = fileContent.IndexOf("mystring") >= 0;