views:

115

answers:

3

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?

+6  A: 

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.

Jay Riggs
+7  A: 

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)

thecoop
A: 

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.

Charlie Salts