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

I think this is what you want...

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

Hi the easiest way to achieve what you're asking for would be something like this:

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 回答