Question

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!

Was it helpful?

Solution 3

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!

OTHER TIPS

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

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top