Search code examples
c#windowsvb.netdirectory

How to use %username% wildcard in paths for IO functions


I would like to have a folder which contains a folder for each user accessing it.

C:\bla\blabla\user1
C:\bla\blabla\user2
etc

How can I use the Windows %username% wildcard to do this in .NET?

This, for example:

IO.Directory.CreateDirectory("C:\bla\blabla\%username%")

Just gives me a folder called exactly "C:\bla\blabla\%username%\"


Solution

  • %username% is an environment variable in Windows that returns the current user's username.

    VB.NET provides us with property that does the same thing, Environment.UserName: https://learn.microsoft.com/en-us/dotnet/api/system.environment.username

    Here is an example using it along with Path.Combine: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine

    IO.Directory.CreateDirectory(IO.Path.Combine("C:\bla\blabla", Environment.UserName))