I have a couple of blog posts that are in stewing nicely, but they're not really ready yet and I want to get them as right as possible on the first posting to try and make them an authoritative reference I can use later (see suzcook/cbrumme/raymondc/etc.) - however, in the mean time there's been a small need to post about temp files, so I'm taking the opportunity.

One of the cool things that's exposed from kernel32 land up through the base framework is System.IO.Path's GetTempFileName API - no params and a string for return makes it very simple to use, and like any good temp file API it actually creates the zero-byte file on disk for you (no need to introduce a race condition when we don't need to).

Once you have that returned back, though, System.IO gives you a lot of potential ways of writing data (this is just to show the API's - please don't mix encodings in the same file :)

string tempPath = Path.GetTempFileName();

 

BAD APPROACHES

// For UTF16/Unicode - wrong API, wrong usage

string contents = "something I want written";

byte[] contentBytes = Encoding.Unicode.GetBytes(contents);

FileStream stream = File.Open(tempPath, FileMode.Append, FileAccess.Write);

stream.Write(contentBytes, 0, contentBytes.Length);

stream.Close();

 

// For UTF16/Unicode - Right API, wrong usage (no using block)

StreamWriter streamWriter = new StreamWriter(tempPath, true, Encoding.Unicode);

streamWriter.WriteLine("Some data goes here");

streamWriter.Close();

 

VARIOUS GOOD APPROACHES

// If the amount of data to write is small, built in-memory as a string, and written UTF8

File.AppendAll(tempPath, "stuff to append in UTF8");

 

// If the amount of data to write is small, built in-memory as a string, and written Unicode

File.AppendAll(tempPath, "stuff to append in Unicode", Encoding.Unicode);

 

// For writing lots of UTF16/Unicode data - right API, right usage

using (StreamWriter writer = new StreamWriter(tempPath, true, Encoding.Unicode))

{

    writer.WriteLine("Some Unicode (aka UTF16)-written data goes here");

}

 

// For writing lots of UTF8 data - right API, right usage

using (StreamWriter writer = File.AppendText(tempPath))

{

    writer.WriteLine("Some UTF8-written data goes here");

}