Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete images that don't exist in SQL database

I have a table of products in my sql database. Each product has an image and 4 thumbnails. These just store the filename of an image on the hard drive. The problem I have is that over time I have deleted thousands of products but the images still remain on the hard drive.

Now I need to build a script (in c# .net) to remove any orphaned images. I assume the only way is to get a list of products into memory and loop though all the images in the directory to cross reference and remove if they don't exist.

Has anyone come across this before and can you give me any advice?

like image 894
Mark Clancy Avatar asked Jan 24 '26 21:01

Mark Clancy


1 Answers

A quicker way would be to write a procedure that moves all the images that are referenced to a new folder on the same hard drive. Then once you've verified you've got them all delete (or rename if you're feeling nervous) the old folder and finally rename the new one back to the original name.

You should backup the original folder first, just in case.

like image 189
ChrisF Avatar answered Jan 27 '26 10:01

ChrisF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!