file.txtのコンテンツで文字列を検索したいとします。ThisIsOkString
それがない場合は、検索する必要があります。ThisIsBadString
これどうやってするの?ありがとう
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....
これがあなたがそれをすることができる2つの方法です。これがあなたのために働くことを願っています!
方法1。最初の一致のみを見つける:
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;
}
}
}
方法2。ファイル内のすべての一致を検索します。
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
}
これがお役に立てば幸いです。