.net 如何从c#目录中读取所有文件?

jv4diomz  于 2023-04-22  发布在  .NET
关注(0)|答案(5)|浏览(190)

这就是我想做的:
1.选择目录
1.输入字符串
1.以字符串的形式从该目录中读取所有文件。
我想实现的想法是:
选择目录,并输入字符串。从该文件夹转到每个文件。例如,文件夹是:Directory={file1.txt,file2.txt,file3.txt}
我想先去file1.txt,读取所有的文本,变成一个字符串,看看我的字符串是否在那个文件里。如果是:或者转到file2.txt,等等。

3gtaxfhh

3gtaxfhh1#

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

您也可以使用File.ReadAllBytes()File.ReadAllText()代替File.ReadAllLines(),这取决于您的需求。

0pizxfdo

0pizxfdo2#

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给予试试吧。

dbf7pr2w

dbf7pr2w3#

我想这就是你想要的。。

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;
        }
    }
}
slsn1g29

slsn1g294#

你好,实现你所要求的最简单的方法是这样的:

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
    }

}
c0vxltue

c0vxltue5#

// 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;
                }

            }

相关问题