C# – Open a shared file under another user and domain

cimpersonationio

I have a C# console application that needs to read a shared file on a machine in another domain.
When the application tries to access the file an exception occurs as the local user does not have permission to access the shared resource.

Currently I overcome this problem manually by open the shared folder from the run and put the username and password into the windows authentication dialog then run the application.

How can I do it programmatically?

Best Answer

a) p/invoke LogonUser with LOGON32_LOGON_NEW_CREDENTIALS and create a new WindowsIdentity with the new token, then use normal file access.

b) p/invoke WNetAddConnection3. Be advised that this makes your remote share accessible to every other process on your machine.

c) WMI via System.Management and CIM_DataFile; you won't even need p/invoke. System.Management lets you specify credentials for remote machine.