简体   繁体   English

如何使用C#连续读取文件夹中的文件?

[英]How to continuously read files in a folder using C#?

I'd like to continuously read in all image files from a folder on my local drive, then do some processing and end the program once all images have been read. 我想从本地驱动器上的文件夹中连续读取所有图像文件,然后进行一些处理并在读取完所有图像后结束程序。 The images numbers are not sequential they are random however they are located in a single folder. 图像编号不是连续的,它们是随机的,但是它们位于单个文件夹中。 Currently my program can only read in one file; 目前,我的程序只能读取一个文件。 see code below 见下面的代码

string imagePath = Path.Combine(Freconfig.GetSamplesFolder(), "24917324.jpg");

use FileSystemWatcher https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx 使用FileSystemWatcher https://msdn.microsoft.com/zh-cn/library/system.io.filesystemwatcher(v=vs.110).aspx

FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Freconfig.GetSamplesFolder();
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    watcher.Filter = "*.jpg";

    // Add event handlers.
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.Deleted += new FileSystemEventHandler(OnChanged);
    watcher.Renamed += new RenamedEventHandler(OnRenamed);

    // Begin watching.
    watcher.EnableRaisingEvents = true;

before starting watcher, use directorylisting to find all existing files and process them, then use watcher 在启动监视程序之前,请使用目录列表查找所有现有文件并进行处理,然后使用监视程序

Is this what you are looking for? 这是你想要的? Directory.GetFiles(@"..\\somepath") ( MSDN ) Directory.GetFiles(@"..\\somepath")MSDN

You could try: 您可以尝试:

directoryInfo = new DirectoryInfo("C:/YOUR/DIRECTORY/HERE]");
var files = directoryInfo.GetFiles("*.jpg").OrderBy(x => x.CreationTimeUtc);
foreach (var file in files)
{
 //Your processing
}

Note this will get all the .jpg files in a directory. 请注意,这会将所有.jpg文件保存在目录中。 The foreach loop will start with the oldest files first. foreach循环将首先从最早的文件开始。

This should get all the files in a directory: 这应该获取目录中的所有文件:

 private List<FileInfo> GetFileInfo()
    {
        string path = @"C:\MyPath";
        List<FileInfo> files = new List<FileInfo>();
        DirectoryInfo di = new DirectoryInfo(path);

       //TopDirectoryOnly if you don't want subfolders
        foreach (FileInfo f in di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly))
        {
            files.Add(f);
        }

        return files;
    }

Then in your code, iterate over the returned collection and do whatever work you need to do with them. 然后在您的代码中,对返回的集合进行迭代,并执行您需要对它们进行的所有工作。

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

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