KnowDotNet Visual Organizer

Using Windows Temp Files

by William Ryan
Print this Article Discuss in Forums

Have you ever needed to write to a file temporarily?  Of couse not ;--).  Anyway, you can do it the 'old' way, and use a specific filename, make sure it doesn't exist, delete it if it does and then write over it.  Or you can do it the easy way.  Below is the code you need to create a temp file and write some nonsensical text to it.  When it's done, you can simply delete it, or just let windows do it the next time the user reboots the machine:



VB.NET

'Returns Tempfile Path
Dim FileName As String = Path.GetTempFileName()

Dim File_Stream As New FileStream(FileName, FileMode.Append, FileAccess.Write)
Dim FileWriter As New StreamWriter(File_Stream)
'Write the Data
With FileWriter
  
Try
      .BaseStream.Seek(0, SeekOrigin.End)
      .WriteLine("Whatever you want to write")
      .WriteLine("A little more of what you want to write")
      .WriteLine("Babba Booeee")
      
Catch ex As IOException
          Debug.Assert(
False, ex.ToString)
      
Finally
          .Close()
  
End Try

End
With


C#

string FileName = Path.GetTempFileName();
FileStream File_Stream =
new FileStream(FileName, FileMode.Append, FileAccess.Write);
StreamWriter FileWriter =
new Stream(File_Stream);
try
{
    FileWriter.BaseStream.Seek(0, SeekOrigin.End);
    FileWriter.WriteLine("Whatever you want to write");
    FileWriter.WriteLine("A Little more ");
    FileWriter.WriteLine("Babba Booeey");
}
catch(IOException ex)
{
    Debug.Assert(
false, ex.ToString());
}
finally
{
    FileWriter.Close();
}

That's all there is to it!  Depending on what you want to do, you may want to throw a delete in the Finally block, but like I mention above, you can also just let Windows do it for you.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing