1

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!

JJJ
  • 32,902
  • 20
  • 89
  • 102
berm
  • 27
  • 9

3 Answers3

0

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
Scott Selby
  • 9,420
  • 12
  • 57
  • 96
0

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"
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
  • It would be safer to use `Dim fileLoc As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "downloads\users.txt")`. – Andrew Morton Dec 13 '13 at 22:52
0
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!

berm
  • 27
  • 9