Library code snippets

The Trick to Temporary Files

Temporary files are incredibly useful. Most applications use them to store information while running some sort of processing. And you can too. When you’re finished, either delete the temporary file or leave it for the next Windows “Disk Cleanup” operation to thwart.

But how do you go about working with temporary files? Well, firstly you need to get a temporary filename, and the System.IO.Path has a shared function called GetTempFileName to help you here. Then you simply write to the file as normal. This handy little function wraps all this functionality up for you into one neat function. Simply call WriteToTempFile and pass in your data. It’ll return your temporary file path:

Public Function WriteToTempFile(ByVal Data As String) As String
    ' Writes text to a temporary file and returns path
    Dim strFilename As String = System.IO.Path.GetTempFileName()
    Dim objFS As New System.IO.FileStream(strFilename, _
    System.IO.FileMode.Append, _
    System.IO.FileAccess.Write)
    ' Opens stream and begins writing
    Dim Writer As New System.IO.StreamWriter(objFS)
    Writer.BaseStream.Seek(0, System.IO.SeekOrigin.End)
    Writer.WriteLine(Data)
    Writer.Flush()
    ' Closes and returns temp path
    Writer.Close()
    Return strFilename
End Function

Here’s how you might call this function in your code:

Dim strFilename As String = WriteToTempFile("This is my data for the temporary file.")
MessageBox.Show(strFilename)

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of The Trick to Temporary Files.

Leave a comment

Sign in or Join us (it's free).

Karl Moore

Related podcasts

  • xpert to Expert: Inside Concurrent Basic (CB)

    "Concurrent Basic extends Visual Basic with stylish asynchronous concurrency constructs derived from the join calculus. Our design advances earlier MSRC work on Polyphonic C#, Comega and the Joins Library. Unlike its C# based predecessors, CB adopts a simple event-like syntax familiar to VB progr...

We'd love to hear what you think! Submit ideas or give us feedback