Question

The user needs to login with his windows credentials at startup of our application. These credentials are used to impersonate the user and run the main form under the provided login. We do now have an OpenFileDialog where the user can select files.

The problem arises now when the user accesses a mapped network drive (the ones are shown from the user logged on to the machine and not my program somehow). When pressing the OK button, the OpenFileDialog displays an error message (path cannot be found/accessed. make sure it exists).

As I have seen in other posts, it would be possible to map these path back to UNC path, but the dialog doesn't even return so I could do this. Is there some workaround other than making my own open file dialog?

Impersonation part:

bool success = NativeMethods.LogonUser(userName, domain, password, (int)LogonType.Logon32LogonNewCredentials, (int)LogonProvider.Logon32ProviderWinnt50, ref pExistingTokenHandle);
if (success)
{
    success = NativeMethods.DuplicateToken(pExistingTokenHandle, (int)SecurityImpersonationLevel.SecurityImpersonation, ref pDuplicateTokenHandle);
    if (success)
    {
        // Return the impersonation context
        WindowsIdentity identity = new WindowsIdentity(pDuplicateTokenHandle);
        impersonationContext = identity.Impersonate();
        return impersonationContext;
    }
}

Open dialog part

OpenFileDialog openFileDialog = new OpenFileDialog
{
    Multiselect = true,
    InitialDirectory = Environment.CurrentDirectory,
    Title = "Select file"
};
bool? dialogResult = openFileDialog.ShowDialog(this);
if (dialogResult.Value)
{
    openFileDialog.FileNames.ToList().ForEach(t => MessageBox.Show("File: " + t));
}
Was it helpful?

Solution

Undoing impersonation before showing the dialog has solved the issue of selecting files on a network drive. The question itself is still valid as also service accounts may need to access network drives.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top