0

I have a function that checks for presence of files in a particular folder and if the files have the data that is not present in the main database i write that data to main db and delete the file i am using Directory.EnumerateFiles to get the list of files and then i iterate through this list to check if they are present in the db, i want to return from the function if the list is empty how to check if list that i got is empty,if i debug and the folder has no files it shows Enumeration did not produce the results.

    private void GetListOfFiles()
    {
        string sourceDirectory = pathOfXmlFiles;
        if (!Directory.Exists(sourceDirectory))
        {
            return;
        }
        var xmlFiles = Directory.EnumerateFiles(sourceDirectory, "*.xml");
        foreach (var item in xmlFiles)
        {
            ReadXmlFile(item);
        }
        foreach (var item in xmlFiles)
        {
            if (_writtenToDb)
            {
                File.Delete(item);
            }
        }
    }

i check for the presence of these files using a different thread that has a timer that fires every 25 seconds , i never do stop the timer can this lead to memory leaks?

4

1 回答 1

2

You don't need to do anything. If xmlFiles is empty both foreach loops won't do anything since there are no objects to iterate over.

However, if you really need to explicitly return if there are no files, use this:

if(!xmlFiles.Any())
    return;

Dont forget to add using System.Linq; at the top of your source file.


As you are enumerating multiple times over the returned files, I suggest you use Directory.GetFiles instead. This will return an array with all files. This will avoid multiple hits to the disk for querying the existing files.

于 2012-09-03T08:20:24.233 回答