-4

file.txtのコンテンツで文字列を検索したいとします。ThisIsOkStringそれがない場合は、検索する必要があります。ThisIsBadString

これどうやってするの?ありがとう

4

4 に答える 4

1
var text = File.ReadAllText(filename); 
bool b = text.Contains("ThisIsOkString");
于 2012-12-03T13:16:54.550 に答える
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;
        }
    }
}
于 2012-12-03T13:21:13.420 に答える
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....
于 2012-12-03T13:21:24.537 に答える
0

これがあなたがそれをすることができる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
                }

これがお役に立てば幸いです。

于 2013-12-14T00:24:21.377 に答える