简体   繁体   English

按文件读取目录文件

[英]Reading a directory file by file

Is it possible to read files from a directory one file after another? 是否可以一个接一个地从一个目录中读取文件?

I look for something like: 我寻找类似的东西:

while (File file = Directory.GetFile(path)) {
    //
    // Do something with file
    //
}

[UPDATE] [UPDATE]

I already knew about GetFiles() but I'm looking for a function that return one file at a time. 我已经知道了GetFiles(),但我正在寻找一个一次返回一个文件的函数。

EnumerateFiles() is .Net4.x, would be nice to have, but I'm using .Net2.0. EnumerateFiles()是.Net4.x,很高兴,但我使用的是.Net2.0。 Sorry, that I didn't mention. 对不起,我没提。

(Tag updated) (标签已更新)

You can enumerate over the file names: 您可以枚举文件名:

foreach(string fileName in Directory.EnumerateFiles(path)) {

    // Do something with fileName - using `FileInfo` or `File`

}
string[] arFiles = Directory.GetFiles(@"C:\");

foreach (var sFilename in arfiles)
{
    // Open file named sFilename for reading, do whatever
    using (StreamReader sr = File.OpenText(sFilename )) 
    {
        string s = "";
        while ((s = sr.ReadLine()) != null) 
        {
            Console.WriteLine(s);
        }
    }
}
foreach (var file in Directory.EnumerateFiles(path))
{
    var currFileText = File.ReadAllText(file);
}

What about Directory.GetFiles(path) method? 那么Directory.GetFiles(path)方法怎么样?

foreach(String fileName in Directory.GetFiles(path))
{
    FileInfo file = new FileInfo(fileName);
}

Try with this... 试试这个......

 foreach (var filePath in Directory.GetFiles(path))
            {
                var text = File.ReadAllText(filePath);
                // Further processing
            } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM