I'm accessing other server with the login credentials. My problem is if I run the code initially, it wil show the error as
Logon failure: unknown user name or bad password
but if I try running the code after connecting to the server once through the command prompt. Then, the application works fine and it does not throw any error. So, daily I need to connect to server once through command prompt in order to run the application without errors.
Here is my code:
static void main()
{
string sourceDir = "//server.domain.mhc//drive";
string DestinationDir = "D:\\Test";
DirectoryCopy(sourceDir, DestinationDir, true);
}
[DllImport("advapi32.DLL", SetLastError = true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
clsEmail objEmail = new clsEmail();
try
{
IntPtr admin_token = default(IntPtr);
if(LogonUser("myusername","domain","pwd",9,0,ref admin_token) != 0)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
}
Found out the solution. See the updated code for the answer.