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)

You might also like...

Comments

Karl Moore

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Weeks of coding can save you hours of planning.”