简体   繁体   中英

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 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 )

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. The foreach loop will start with the oldest files first.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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