Accessing a file on a network drive

Posted by Rekreativc on Stack Overflow See other posts from Stack Overflow or by Rekreativc
Published on 2010-03-23T15:40:22Z Indexed on 2010/03/23 15:43 UTC
Read the original article Hit count: 433

Filed under:
|

Hello.

Background: I have an application that has to read from files on a network drive (Z:)

This works great in my office domain, however it does not work on site (in a different domain). As far as I can tell the domain users and network drives are set in the same way, however I do not have access to users etc in the customers domain.

When I couldn't access the network drive I figured I needed a token for a user. This is how I impersionate the user:

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

...

const string userName = "Razvoj02";
const string pass = "Programer02";
const string domainName = null;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;

IntPtr tokenHandle = new IntPtr(0);

bool returnValue = LogonUser(userName, domainName, pass,
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            ref tokenHandle);

if (!returnValue)
    throw new Exception("Logon failed.");

WindowsImpersonationContext impersonatedUser = null;
try
{
    WindowsIdentity wid = new WindowsIdentity(tokenHandle);
    impersonatedUser = wid.Impersonate();

}
finally
{
    if (impersonatedUser != null) impersonatedUser.Undo();
}

Now here is the interesting/weird part. In my network the application can already access the network drive, and if I try to impersonate the active user (exactly the same user, including the same domain) it will not be able to access the network drive.

This leaves me helpless since now I have no idea what works and what doesn't, and more to the point, will it work on site?

What am I missing?

© Stack Overflow or respective owner

Related posts about c#

Related posts about networkdrive