Question

I need to create some bitmaps and save them to the file system. For some reason the MScharting system wants it's background files supplies as paths in string form.

I'm dynamically creating the background image, although only a few times.

What's the best way to create these files and then clean them up?

Was it helpful?

Solution

Your best bet is to have a TemporaryFileManager that implements IDisposable; you ask it for temporary files, which it auto-generates and sticks in a temp directory somewhere, then they all get deleted when the TemporaryFileManager gets disposed, either by you or the finalizer (if you've implemented the disposable pattern correctly)

OTHER TIPS

Here's how you can get the full path and file name of a temporary file:

string tempFile = System.IO.Path.GetTempFileName();

Create the file using this filename & path and when you're done delete it.

In my projects, I have a helper class called TempFile. It has several static methods that I use to write a stream (or an array of bytes if need be) to a temporary file. Here's a simplified example of such a method:

public static string Write(Stream stream)
{
   string FileName = Path.GetTempFileName();

   // Write the contents of stream to a file with FileName

   return FileName;
}

Then, I have another method that accepts a file path for later deletion which is a member of my 'parsing' class, although you could put it in its own static helper class:

public string ForDeletion(string path)
{
   ListOfPaths.Add(path);

   return path;
}

Finally, I do the following:

SomeApiFunction(ForDeletion(TempFile.Write(myStream)));

This is the best way I've come up with for circumventing an API's lack of stream handling capabilities.

I use this solution:

using System.IO;
using System.Reflection;

namespace Konard.Helpers
{
    public static partial class TemporaryFiles
    {
        private const string UserFilesListFilenamePrefix = ".used-temporary-files.txt";
        static private readonly object UsedFilesListLock = new object();

        private static string GetUsedFilesListFilename()
        {
            return Assembly.GetEntryAssembly().Location + UserFilesListFilenamePrefix;
        }

        private static void AddToUsedFilesList(string filename)
        {
            lock (UsedFilesListLock)
            {
                using (var writer = File.AppendText(GetUsedFilesListFilename()))
                    writer.WriteLine(filename);
            }
        }

        public static string UseNew()
        {
            var filename = Path.GetTempFileName();
            AddToUsedFilesList(filename);
            return filename;
        }

        public static void DeleteAllPreviouslyUsed()
        {
            lock (UsedFilesListLock)
            {
                var usedFilesListFilename = GetUsedFilesListFilename();

                if (!File.Exists(usedFilesListFilename))
                    return;

                using (var listFile = File.Open(usedFilesListFilename, FileMode.Open))
                {
                    using (var reader = new StreamReader(listFile))
                    {
                        string tempFileToDelete;
                        while ((tempFileToDelete = reader.ReadLine()) != null)
                        {
                            if (File.Exists(tempFileToDelete))
                                File.Delete(tempFileToDelete);
                        }
                    }
                }

                // Clean up
                using (File.Open(usedFilesListFilename, FileMode.Truncate)) { }
            }
        }
    }
}

Every time you need temporary file use:

var tempFile = TemporaryFiles.UseNew();

To be sure all temporary files are deleted after application closes or crashes put

TemporaryFiles.DeleteAllPreviouslyUsed();

at start of the application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top