Posts Tagged ‘Network’
C#: Accessing resources on network
Accessing files and other resources on network from within code is achieved in following way in C# (of course there are other ways but this seems neat):
Take following assembly reference first:
using System.Runtime.InteropServices;
[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);
Private void YourFunction()
{
WindowsImpersonationContext wic;
IntPtr tokenHandle = new IntPtr(0);
bool returnValue = LogonUser(f.cUserName, f.cDomain, f.cPassword, 2, 0, ref tokenHandle);
WindowsIdentity ImpersonatedIdentity = new WindowsIdentity(tokenHandle);
WindowsImpersonationContext MyImpersonation = ImpersonatedIdentity.Impersonate();
wic = MyImpersonation;
// do some file IO activity here on server…
wic.Undo();
}
multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed
multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed
This message will come when you have already connected to a network machine earlier using some credential and now you are trying to access the same machine using a different set of credentials. The reason is, windows keep the connection open once we open a network path using a particular credential and does not close until we shutdown.
Solution is we remove those connections manually and a simple trick is following command which deletes all “saved” connections:
net use * /delete
Or, you can delete a specific by using :
net use \\192.168.1.100 /delete