Greg
Greg

Reputation: 11480

Quirky Directories

I've got an issue with some directory manipulation.

The problem is I have an archive of data that needs to be add or purge backup data based on a series of constraints. The constraint that is an issue is the archive only needs to keep the backup from the previous week.

So when you chart out the steps you would assume:

The problem though is when you try keep the code simple and implementation, you create some code that doesn't feel like it is proper practice.

string[] archiveFiles = Directory.GetFiles(
     Archive, @"*.*", SearchOption.TopDirectoryOnly);

foreach(string archive in archiveFiles)
     File.Delete(archive);

So if you attempt to grab the files with Directory.GetFiles() and it doesn't return a value, according to the documentation:

Return Value Type: System.String[] An array of the full names (including paths) for the files in the specified directory that match the specified search pattern and option, or an empty array if no files are found.

If it returns a null in the array then that would actually have the loop iterate once, an error. If it returns an array with no elements then it will ignore the loop. The second is what I believe it does, which makes this approach feel incorrect.

The only thing I could do would be to use File.Copy() as it can overwrite files, which would avoid this approach but even that could become suceiptable to the same dilemma of that empty array.

Is that right usage and approach for Directory.GetFiles() or is there a better way?

Upvotes: 0

Views: 63

Answers (1)

Valentin Kuzub
Valentin Kuzub

Reputation: 12073

If it returns a null in the array then that would actually have the loop iterate once, an error. If it returns an array with no elements then it will ignore the loop. The second is what I believe it does, which makes this approach feel incorrect.

If there are no files matching the list will be empty, there won't be nulls (how many nulls should return an empty directory?).

So your delete code will not be executed. Makes sense to me.

If you need to delete old files, then copy the new ones you may want to first move old files somewhere safe, then copy new ones, then to delete old files.

Maybe I didnt understand the problem here, but I don't see any. I hope actual code has some try catches though.

Upvotes: 1

Related Questions