1

I am creating a winforms document manager. I would like to allow the user to upload to and open documents from a protected network drive.

A specific username and password will be setup for the application so that only the application can access the files.

Normally when I allow the user to open a file I use the OpenFileDialog command. How do I add the username and password?

Thanks.

EDIT

Found some additional code:

Public Class ImpersonateUser

Private Declare Auto Function LogonUser Lib "advapi32.dll" ( _
    ByVal lpszUsername As String, _
    ByVal lpszDomain As String, _
    ByVal lpszPassword As String, _
    ByVal dwLogonType As Int32, _
    ByVal dwLogonProvider As Int32, _
    ByRef phToken As IntPtr _
) As Int32


Private Declare Auto Function ImpersonateLoggedOnUser Lib "advapi32.dll" ( _
    ByVal hToken As IntPtr _
) As Int32


Declare Auto Function RevertToSelf Lib "advapi32.dll" ( _
) As Int32


Private Function ImpersonateValidUser( _
    ByVal Username As String, _
    ByVal Domain As String, _
    ByVal Password As String _
) As Boolean
    Dim LogonType As Int32
    Dim LogonProvider As Int32
    Dim Tk As IntPtr
    LogonType = 2     ' Interactive. 
    LogonProvider = 0 ' Default Provider. 
    If LogonUser(Username, Domain, Password, LogonType, LogonProvider, Tk) <> 0 Then
        Return (ImpersonateLoggedOnUser(Tk) <> 0)
    End If

    Return False
End Function


Private Sub UndoImpersonation()
    RevertToSelf()
End Sub


Sub test()

    If ImpersonateValidUser("accountname", "Domainname", "password") Then


        ' This code runs unter the privileges of the impersonated user. 
        Process.Start("C:\foo.exe")
        UndoImpersonation()
    End If
End Sub


End Class

Credit to the original author, is there any advantages/disadvantages to using this method?

Reafidy
  • 8,240
  • 5
  • 51
  • 83
  • 1
    Do you have a user authentication system in place already for your users? If so, what kind is it? – Brian Webster Jun 13 '11 at 02:00
  • Most of our clients will be using windows server, so active directory. Im open to all suggestions though. – Reafidy Jun 13 '11 at 02:15
  • check this link [Accessing Password Protected Network Drives in Windows in C#?](https://stackoverflow.com/questions/2563724/accessing-password-protected-network-drives-in-windows-in-c) – DeveloperX Jun 13 '11 at 15:28
  • Thanks I had seen that link, but stupidly dismissed it for some reason, I presume you are referring to the code and not one of the links. Can you tell me - what is the danger of the application failing while in the middle of impersonating? Will windows still function normally for the original user? – Reafidy Jun 14 '11 at 03:10
  • Also: I have just found the "advapi32.dll" library see my edit above. Which method is more realiable? – Reafidy Jun 15 '11 at 21:53
  • The code does not work for me as Process.Start does not run under impersonation so I cannot open the file. – Reafidy Jun 22 '11 at 03:15

0 Answers0