1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Creating Temporary File in .Net

Discussion in 'Visual Basic [VB]' started by pradeep, Jun 13, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Temp files are generally used for temporary storage and data manipulation. This is often necessary for storing user data, user preferences, session information, application cache, and many other types of information.

    In order to get the name of the file that you can use as a temp file in VB.NET, I suggest using the GetTempFileName method of the Path class. While there are multiple approaches to creating a temp file, it's really helpful to use the System.IO.Path because it returns a unique file name in the current user's temporary directory; you can use that file name to create a file for storing temporary information. Note that calling this method multiple times will result in getting a different file name each time even if you don't use that name to create a file. This behavior prevents name collisions between multiple applications.

    Snippet A
    Code:
     Private Sub TempFile()
         Dim sTempFileName AsString = System.IO.Path.GetTempFileName()
         Dim fsTemp AsNew System.IO.FileStream(sTempFileName, IO.FileMode.Create)
     
         MessageBox.Show(sTempFileName)
     
         'write data to the temp file
         fsTemp.Close()
     
         System.IO.File.Delete(sTempFileName)
     End Sub
     
    In the sample code in Snippet A, I define the string variable, sTempFileName, and assign the System.IO.Path.GetTempFileName method's return value to it. This produces a temp file name that I can use. I then create a FileStream object, fsTemp, and request that the system create a file with the filename, sTempFileName. Once the file is created, I add data to it (this code is omitted in the example). After that, the temp file is closed.
     
  2. rozerdemit

    rozerdemit New Member

    Joined:
    Jan 4, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Wow great example thanks for posting here,,,,,,,,,,
     
  3. rozordermit

    rozordermit New Member

    Joined:
    Mar 19, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi dude, That's really good to see the example like this.
     

Share This Page