locked
How does one create a unique-filename temp file in VB? RRS feed

  • Question

  • WHAT I HAVE:

    Visual Basic 2010, .NET 4.0, EF 4.0

    MY PROBLEM:

    I want to be able to create a unique file name--so that I can safely create and delete a temporary file without affecting any pre-existing file--for my WinForms VB 2010 application.


    Robert Gustafson


    Sunday, May 11, 2014 3:34 AM

Answers

All replies

  • Hi, you can use System.IO.Path.GetTempFileName() to create a unique file name:

    http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx
    • Edited by lapheal Sunday, May 11, 2014 4:41 AM
    • Proposed as answer by Devon_Nullman Sunday, May 11, 2014 1:19 PM
    • Marked as answer by RobertGustafson Sunday, May 11, 2014 9:04 PM
    Sunday, May 11, 2014 4:40 AM
  • http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx

    dim filename  as string = Guid.NewGuid().Tostring & ".fle"

    Sunday, May 11, 2014 4:46 AM
  • Naming Files, Paths, and Namespaces

    I do it like this

    My.Computer.FileSystem.WriteAllText("C:\Users\John\Desktop\MrMonkeyboy.MonkeyBusiness", TextBox1.Text, False)

    Text from file opened in Notepad.

    Hello World


    La vida loca

    Sunday, May 11, 2014 4:58 AM
  • Imports System.IO
    Imports System.Security.Cryptography
    Module Module1
        Sub Main()
            Dim Filenamelength As Integer = 20
            Dim RNG As New RNGCryptoServiceProvider
            Dim CharBuffer(9999) As Byte
            Dim FullPath As String = ""
            Dim Filename As String = ""
            Dim ThePath As String = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
            Do
                Filename = ""
                FullPath = ""
                RNG.GetBytes(CharBuffer)
                For Each b As Byte In CharBuffer
                    If (b >= Asc("A") And b <= Asc("Z")) Or (b >= Asc("a") And b <= Asc("z")) Or (b >= Asc("0") And b <= Asc("9")) Then
                        Filename &= Chr(b)
                        If Filename.Length >= Filenamelength Then
                            Exit For
                        End If
                    End If
                Next
                Filename &= "." & Guid.NewGuid.ToString.Substring(0, 4)
                FullPath = Path.Combine(ThePath, Filename)
            Loop Until Not File.Exists(FullPath)
            Console.WriteLine(FullPath & " is unique and can be used")
            Console.ReadLine()
        End Sub
    End Module
    

    Sunday, May 11, 2014 8:32 PM