user3630916
user3630916

Reputation: 23

how to see if a text file exist in documents folder in visual basic

in my VB.NET program i have it create a text file that contains a username and password. the Username being on the first line, the password on the second. this works great. I do this because i want it to pre-load the account into the text boxes once the user re-opens the program. so at the beginning, i want it to test if the file exist. the file exist in the directory Documents under 'account.txt'. this is the code that generates the text file:

            Try
            Dim filePath As String
            filePath = System.IO.Path.Combine(
                       My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")
            My.Computer.FileSystem.WriteAllText(filePath, TextBox1.Text + Environment.NewLine + TextBox2.Text, False)
        Catch fileException As Exception
            Throw fileException
    End Try
    MsgBox("Saved account to 'Documents\Account.text' and will auto-fill Username and password box when program is re-opened.")

and this is the code i tried to use to see if it existed or not:

        If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.SpecialDirectories.MyDocuments + "Account.txt") Then
        MsgBox("File found.")
    Else
        MsgBox("File not found.")
    End If

I also tried this:

               If My.Computer.FileSystem.SpecialDirectories.MyDocuments.FileExists("c://Check.txt") Then
        MsgBox("File found.")
    Else
        MsgBox("File not found.")
    End If

The first one cant find it because I know in doing it wrong but the second doesn't work because the syntax it wrong as well. Any help is appreciated greatly.

Upvotes: 0

Views: 3083

Answers (1)

Krishanu Dey
Krishanu Dey

Reputation: 6406

try

Dim filePath As String
filePath = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")

If File.Exists(filePath) Then
    MsgBox("File found.")
Else
    MsgBox("File not found.")
End If

Upvotes: 1

Related Questions