Search code examples
c#.netcachingtemporary-files

How can I create a temporary file to cache startup work for a library?


I am working on a C# library that performs some expensive computation on startup. I would like to cache this computation so that the cost isn't paid each time the application restarts (think EF and pre-compiled views).

The information I would like to cache is easily writable to a file in text format. Thus, I would like to do the following when the library is invoked:

  1. Generate a unique hash of the configuration parameters.
  2. Check if there is a cache file for that hash. If so, read it in and use it to skip the setup computation.
  3. If not, perform the setup computation and generate an appropriate cache file named by a hash of the configuration parameters.

Furthermore, I don't want to permanently litter the users' hard drive such files: I want them to be automatically cleaned up by the operating system (much like temporary files) to the extent that this is possible.

Also, because this is a library I can't depend on other software being installed. Thus, I'd prefer a pure .NET solution.

Can anyone point me to a good method/.NET APIs for doing something like this?


Solution

  • You should probably use ApplicationData directory to store your cache files, e.g.:

    var cacheDir = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), 
        "MyApplicationName");
    

    If you want automatic cleanup you can create an empty cache file during the setup so the file will be deleted automatically when your application is uninstalled. Or write the cleanup method yourself in your application's installer class.

    I don't think that you can rely on operating system to do the cleanup, Windows can't even clean its own garbage files.