Trying to create a good path in vb.net

297 views Asked by At

I'm writing an application that creates some text files. I want them in some folders so I did:

Dim fileLoc As String = "c:\users\%username%\downloads\users.txt"
    If 1 + 1 = 2 Then <--- not very professional but it works! it works....
        Dim fs As FileStream = Nothing
        If (Not File.Exists(fileLoc)) Then
            fs = File.Create(fileLoc)
            Using fs
            End Using
        End If
    End If
    If File.Exists(fileLoc) Then
        Using sw As StreamWriter = New StreamWriter(fileLoc)
            sw.Write(pcname.Text)
        End Using
    End If

But when I try to debug, the following happens:

DirectoryNotFoundException was unhandled Cannot find a part of the path (c:\users\%username%\downloads\users.txt)

I'm sure it's because "%username%" because when I fill in the whole path, it works. But when the program is on another pc it will not work!

3

There are 3 answers

0
berm On BEST ANSWER
Dim fileLoc As String = "c:\users\" & Environment.UserName & "\downloads\users.txt"
If 1 + 1 = 2 Then <--- not very professional but it works! it works....
    Dim fs As FileStream = Nothing
    If (Not File.Exists(fileLoc)) Then
        fs = File.Create(fileLoc)
        Using fs
        End Using
    End If
End If
If File.Exists(fileLoc) Then
    Using sw As StreamWriter = New StreamWriter(fileLoc)
        sw.Write(pcname.Text)
    End Using
End If

This is the correct code! thank you all for thinking with me!

0
Scott Selby On

try some thing like this

Dim userName as string = WindowsIdentity.GetCurrent().Name;

Dim fileLoc As String = "c:\users\" & userName & "\downloads\users.txt"
    If 1 + 1 = 2 Then <--- not very professional but it works! it works....
        Dim fs As FileStream = Nothing
        If (Not File.Exists(fileLoc)) Then
            fs = File.Create(fileLoc)
            Using fs
            End Using
        End If
    End If
    If File.Exists(fileLoc) Then
        Using sw As StreamWriter = New StreamWriter(fileLoc)
            sw.Write(pcname.Text)
        End Using
    End If
1
Yuriy Galanter On

I don't think you can use environmental variables like this.

Instead

Dim fileLoc As String = "c:\users\%username%\downloads\users.txt"

Try

Dim fileLoc As String = "c:\users\" & Environment.UserName & "\downloads\users.txt"