Microsoft & .NETVisual BasicThe Trick to Temporary Files

The Trick to Temporary Files content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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 = _
  Dim objFS As New System.IO.FileStream( _
     strFilename, _
     System.IO.FileMode.Append, _
  ' Opens stream and begins writing
  Dim Writer As New System.IO.StreamWriter(objFS)
  Writer.BaseStream.Seek(0, _
  ' Closes and returns temp path
  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 _

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories