假设我想要将file.txt的搜索内容用于字符串ThisIsOkString
,如果不是,那么我应该搜索ThisIsBadString
我该怎么做? 感谢
答案 0 :(得分:1)
var text = File.ReadAllText(filename);
bool b = text.Contains("ThisIsOkString");
答案 1 :(得分:1)
var myFile = "C:\\PathToDirectory";//your folder
bool doesExist = Directory.Exists(myFile);
if (doesExist)
{
string content = File.ReadAllText(myFile + "\\myFile.txt");//your txt file
string[] searchedText = new string[] { "ThisIsOkString", "ThisIsBadString" };
foreach (string item in searchedText)
{
if (searchedText.Contains(item))
{
Console.WriteLine("Found {0}",item);
break;
}
}
}
答案 2 :(得分:0)
using(StreamReader sr = new StreamReader)
{
a = false;
string line;
while((line = sr.ReadLine()) != null)
{
if(line.Contains("Astring")
a = true;
break;
}
}
file.close();
if a = true....
答案 3 :(得分:0)
这有两种方法可以做到。希望这对你有用!
方法一。仅查找第一场比赛:
using (StreamReader sr = new StreamReader("Example.txt"))
{
bool done = false;
while (done == false)
{
string readLine = sr.ReadLine();
if (readLine.Contains("text"))
{
//do stuff with your string
Console.WriteLine("readLine");
sr.Close();
done = true;
}
}
}
方法二。查找文件中的所有匹配项:
using (StreamReader sr = new StreamReader("Example.txt"))
{
string readLine = "text"; //this text has to have at least one character for the program to work
int line = 0; //this is to keep track of the line number, it is not necessary
while (readLine != "") //make sure the program doesn't keep checking for the text after it has read the entire file.
{
readLine = sr.ReadLine();
line ++; //add one two the line number each time it searches, this searching program searches line by line so I add one just after it searches each time
if (readLine.Contains("text"))
{
//do stuff with your string
Console.WriteLine(line + ": readLine"); //you don't have to write it to the screen. You can do absolutely anything with this string now, I wrote the line number to the screen just for fun.
}
}
sr.Close(); //once the search is complete, this closes the streamreader so it can be used again without issues
}
希望这能帮到你!