Getting a directory size
Published 12.16.2005 by ~mattg
The aforementioned consulting project has led me to rewrite a good portion of their photo gallery code. Their initial storage solution was horrendous, causing the database to become exceptionally large, increasing the number of calls to the DB (not to mention the size of each transaction itself), and not allowing me to do things with javascript that are essential if you want a decent UI on the web.
So I rewrote the photo album, adding a caching system that, while primative, gets the job done. It basically stores the photos on the server and then dynamically creates thumbnails, full-size images, and slide show slides as necessary. Not bad.
The problem I have is that I don’t want the cache to grow to large. The clean way to do it would be to keep track of a cached file’s creation date, and delete files that are older than, say, a week. If they are needed they can be recreated. The dirty way to do it is to delete all the cached files.
Right now, the dirty way is being implemented. However, it must have taken me a half hour of searching to locate a halfway decent method of finding out the size of files on disk for a particular directory. I tried everything from the GetDiskFreeSpaceEx API call to the ManagementClass object in the .Net framework. It would figure, though, that the easiest solution simply involved recursing the given directory and adding all it’s files sizes up. This MSDN article has more detail.
It’s not elegant, but it works… So I’m using it, at least until I can implement the clean solution.
Filed under News