Samuel Nicholson
Samuel Nicholson

Reputation: 3629

VB.net use string in Directory Path?

I apologise for my lack of basic VB.net knowledge but I'm looking to use the equivalent of %systemdrive% to find the drive containing Windows to check for an existing directory in VB.net - so I have the below.

Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
        If Not Directory.Exists("'systemPath'\MyFolder") Then
            Directory.CreateDirectory("'systemPath'\MyFolder")
        End If

Can someone help with using the systemPath string in the directory query? Thank you.

Upvotes: 0

Views: 1244

Answers (2)

dbasnett
dbasnett

Reputation: 11773

IO.Path has methods that should be used IMHO

    Dim sysDrive As String = Environment.GetEnvironmentVariable("SystemDrive") & IO.Path.DirectorySeparatorChar
    Dim myPath As String = IO.Path.Combine(sysDrive, "FolderName")

Upvotes: 0

Steve
Steve

Reputation: 216293

Well you should write

Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
If Not Directory.Exists(Path.Combine(systemPath, "MyFolder")) Then
        Directory.CreateDirectory(Path.Combine(systemPath, "MyFolder"))
End If

You could get the environment variable called %SYSTEMDRIVE% with Environment.GetEnvironmentVariable, but then the results obtained should be manually combined with current directory separator char ("\") because I have not found any way to convince Path.Combine to build a valid path with only the system drive (I.E. C: )

Dim sysDrive = Environment.GetEnvironmentVariable("SystemDrive") 
Dim myPath = sysDrive & Path.DirectorySeparatorChar & "MyFolder" 

Upvotes: 1

Related Questions