问题
We have a thick-client that needs to access resources on a share where a client may not be logged on. The client might be on a Windows domain or it could be a mixed environment without a domain, so the user would have to log on to the server locally. In the past, one work around was to create a shortcut on the user's desktop to the share, which opens Windows Explorer, which opens a password prompt that grants or denies access to the share. How can I get the user to signon to the share without relying on Windows Explorer? What does Windows Explorer do that I can have my app do to demand access to the share?
I have read Access files from network share in c# web app, but I am doing this in a WinForms app and want it to be interactive. I have also read How to prompt for a Password, but that code just prompts for strings from the user rather than invoking the UI that demands and grants access to the share. I would rather not have my app know the user's password as much as trigger the OS to demand access for the network resource.
回答1:
You could take a look at the Win32 API CredUIPromptForCredentials ( or CredUIPromptForWindowsCredential if you're running on Vista/Win2k8, you should check the winver to decide which call to make).
This method actually invokes the regular credentials prompt but you get the credentials (awful, I know).
PInvoke.Net has sample code showing how to call this function from C# (in the PInvoke sample you have to pass CREDUI_FLAGS.DO_NOT_PERSIST for flags if you've specified false in save. Weird, I know).
More info (and a unmanaged sample) on the great Keith brown wikibook on security
Once you get the credentials (in a secure string) you can then impersonate the user to get to the resource (using logonuser).
And it's ugly. I understand you want Windows to show the standard prompt dialog and you don't want to know about the credentials.
I'm wondering if a ugly hack like using System.Diagnostics.Process to launch a hidden explorer.exe on the remote UNC would not do the trick. You'd have to find a way to wait for the user to have entered the credentials and then kill the spawned explorer process.
来源:https://stackoverflow.com/questions/940529/how-can-i-demand-access-to-a-windows-share-in-a-net-thick-client-app