1

これは私がやりたいことです:

  1. ディレクトリを選択
  2. 文字列を入力
  3. そのディレクトリからすべてのファイルを文字列で読み取ります。

私が実装したいアイデアはこれです:

ディレクトリを選択し、文字列を入力します。そのフォルダから各ファイルに移動します。たとえば、フォルダは次のとおりです。Directory={file1.txt,file2.txt,file3.txt}

最初に file1.txt に移動し、すべてのテキストを文字列に読み取り、文字列がそのファイルに含まれているかどうかを確認します。はいの場合: そうでなければ file2.txt に移動します。

4

5 に答える 5

14
foreach (string fileName in Directory.GetFiles("directoryName", "searchPattern")
{
    string[] fileLines = File.ReadAllLines(fileName);
    // Do something with the file content
}

File.ReadAllBytes()orFile.ReadAllText()の代わりに使用することもできますがFile.ReadAllLines()、要件によって異なります。

于 2012-06-10T18:45:52.163 に答える
4
        var searchTerm = "SEARCH_TERM";
        var searchDirectory = new System.IO.DirectoryInfo(@"c:\Test\");

        var queryMatchingFiles =
                from file in searchDirectory.GetFiles()
                where file.Extension == ".txt"
                let fileContent = System.IO.File.ReadAllText(file.FullName)
                where fileContent.Contains(searchTerm)
                select file.FullName;

        foreach (var fileName in queryMatchingFiles)
        {
            // Do something
            Console.WriteLine(fileName);
        }

これはLINQに基づくソリューションであり、問​​題も解決するはずです。理解しやすく、維持しやすいかもしれません。LINQ を使用できる場合は、試してみてください。

于 2012-06-10T19:43:06.330 に答える
0

これはあなたが望むものだと思います...

string input = "blah blah";
string file_content;
FolderBrowserDialog fld = new FolderBrowserDialog();
if (fld.ShowDialog() == DialogResult.OK)
{
    DirectoryInfo di = new DirectoryInfo(fld.SelectedPath);
    foreach(string f  in Directory.GetFiles(fld.SelectedPath))
    {
        file_content = File.ReadAllText(f);
        if (file_content.Contains(input))
        {
            //string found
            break;
        }
    }
}
于 2012-06-10T18:50:24.387 に答える
0

こんにちは、あなたが求めていることを達成する最も簡単な方法は次のようなものです:

string[] Files = System.IO.Directory.GetFiles("Directory_To_Look_In");

foreach (string sFile in Files)
{
    string fileCont = System.IO.File.ReadAllText(sFile);
    if (fileCont.Contains("WordToLookFor") == true)
    {
        //it found something
    }

}
于 2012-06-10T18:51:08.900 に答える
0
            // Only get files that are text files only as you want only .txt 
            string[] dirs = Directory.GetFiles("target_directory", "*.txt");
            string fileContent = string.Empty;
            foreach (string file in dirs) 
            {
               // Open the file to read from. 
                fileContent = File.ReadAllText(file);                
                // alternative: Use StreamReader to consume the entire text file.
                //StreamReader reader = new StreamReader(file);
                //string fileContent = reader.ReadToEnd();

                if(fileContent.Contains("searching_word")){
                  //do whatever you want
                  //exit from foreach loop as you find your match, so no need to iterate
                    break;
                }

            }
于 2019-01-31T07:44:10.897 に答える