假设我想搜索 file.txt 的字符串内容ThisIsOkString
,如果它不存在,我应该搜索ThisIsBadString
我怎样才能做到这一点?谢谢
var text = File.ReadAllText(filename);
bool b = text.Contains("ThisIsOkString");
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;
}
}
}
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....
这里有两种方法可以做到。希望这对你有用!
方法一。仅查找第一个匹配项:
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
}
希望这对你有帮助!