April 18, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

The Trick to Temporary Files

  • December 1, 2003
  • By Karl Moore
  • Send Email »
  • More Articles »

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)

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 www.karlmoore.com.

# # #






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel