How do I get the same result from this Python script in Visual Basic?

import os
username = os.getenv("USERNAME")
desktop = "C:\\Documents and Settings\\%s\\Desktop\\" % username
print desktop 
#Result = C:\Documents and Settings\<MY USERNAME>\Desktop\

I already have this,

Public Shared username As String = My.User.Name 'Gives computer name then username. That isn't going to work
Public Shared desktop As String = "C:\Documents and Settings\<USERNAME>\Desktop"

Taking it that you are refering to VB6, it is a bit more involved. The following works for Vista as well, not sure on 7 though. -

Private Const MAX_USERNAME As Long = 15

Private Declare Function GetUserName Lib "advapi32" _
   Alias "GetUserNameA" _
  (ByVal lpBuffer As String, _
   nSize As Long) As Long
      
Private Declare Function lstrlenW Lib "kernel32" _
  (ByVal lpString As Long) As Long

        
Private Function GetThreadUserName() As String

  'Retrieves the user name of the current
  'thread. This is the name of the user
  'currently logged onto the system. If
  'the current thread is impersonating
  'another client, GetUserName returns
  'the user name of the client that the
  'thread is impersonating.
   Dim buff As String
   Dim nSize As Long
   
   buff = Space$(MAX_USERNAME)
   nSize = Len(buff)

   If GetUserName(buff, nSize) = 1 Then

      GetThreadUserName = TrimNull(buff)
      Exit Function

   End If

End Function


Private Function TrimNull(startstr As String) As String

   TrimNull = Left$(startstr, lstrlenW(StrPtr(startstr)))
   
End Function


Private Sub Command1_Click()

Text1.Text = GetThreadUserName 'Add user name to textbox or print etc.
End Sub

You can also get the username like so...

Debug.Print Environ("USERNAME")

However, Andre's method is preferred in a lot of cases...

Once you have the username, you can then check for the existence of the desktop by building the string yourself, but the path you are specifing you will not be able to access unless virtualization takes over. To get a path, see...

http://www.codeitbetter.com/how-to-get-the-desktop-path/

or to get the path you are talking about, see...

http://vbnet.mvps.org/index.html?code/shell/desktoplink.htm

Good Luck

Just be carefull of getting the path in Vista. Vista is VERY insecure when it gets to applications that wants to read into its paths, files or reg values, and tend to bomb regularly. At least, that is what I have experienced, mainly on GetSpecialFolderLocation, HKey_Current_User etc.

I have tested the above code in windows 7, works fine.

I tested the first link to code and I am on vista home with UAC turned on and I'm fairly sure that the code in the second link I gave will work also as I have never had a problem with code from that site...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.