How to solve "System.IO.IOException: The user name or password is incorrect" error using asp.net?

22.1k Views Asked by At

I just want to get the folder name which is in a different domain. I can get the folder name when I try to get the folder name locally.

Here is my code

[WebMethod]
public void getAllRootDirectoryNames(string path)
{
    string userName = "Domain\\Admin";
    string password = "Password";
    NetworkCredential theNetworkCredential = new NetworkCredential(userName, password);
    CredentialCache theNetcache = new CredentialCache();

    theNetcache.Add(new Uri(@"\\192.168.x.x"), "Basic", theNetworkCredential);

    List<GetFolderDetails> details = new List<GetFolderDetails>();
    Debug.WriteLine("GET All Root Directory Names START");

    foreach (var directoryName in new DirectoryInfo(path).GetDirectories())
    {
        GetFolderDetails fd = new GetFolderDetails();
        fd.fullFolder = directoryName.Parent.Name;
        fd.folderName = directoryName.Name;

        fd.urlPath = path + directoryName.Name;
        fd.subFolderExists = 0;

        details.Add(fd);
    }

    JavaScriptSerializer js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(details));
}

Error message:

System.IO.IOException: The user name or password is incorrect.

UPDATE

I tried this below code.

[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);

    [WebMethod]
    public void getAllRootDirectoryNames(string path)
    {

        IntPtr tokenHandle = new IntPtr(0);
        tokenHandle = IntPtr.Zero;

        bool returnValue = LogonUser("USerName", "DomainName", "password", 2, 0, ref tokenHandle);
        WindowsIdentity ImpersonatedIdentity = new WindowsIdentity(tokenHandle);
        WindowsImpersonationContext MyImpersonation = ImpersonatedIdentity.Impersonate();


        List<GetFolderDetails> details = new List<GetFolderDetails>();

        foreach (var directoryName in new DirectoryInfo(path).GetDirectories())
        {
            GetFolderDetails fd = new GetFolderDetails();
            fd.fullFolder = directoryName.Parent.Name;
            fd.folderName = directoryName.Name;
            //fd.urlPath = directoryName.FullName;
            fd.urlPath = path + directoryName.Name;
            fd.subFolderExists = 0;


            foreach (var insideDirName in new DirectoryInfo(path + "/" + directoryName.Name + "/").GetDirectories())
            {
                fd.subFolderExists = 1;
            }
            details.Add(fd);
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(details));

        MyImpersonation.Undo();

    }

It throws the following error

'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code

4

There are 4 best solutions below

7
Yurii Maksimov On

I suppose your host and target machine based on Windows. I did it previously but my code looked a little bit different. will try to make some scenario (in nutshell). First import this dll. Check params and play with the formatting of inputs. I really do not remember how they should look.

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

public class TestClass
{
    public void TestMethod()
    {
        IntPtr admin_token = default(IntPtr);
        WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
        WindowsIdentity wid_admin = null;

        WindowsImpersonationContext wic = null;
        try

        {
            if (LogonUser(User, userDomain, Password, DwLogonType, DwLogonProvider, ref admin_token))
            {
                wid_admin = new WindowsIdentity(admin_token);
                wic = wid_admin.Impersonate();
                if (!Directory.Exists(@"C:\TempFiles")) Directory.CreateDirectory(@"C:\TempFiles");
                file.SaveAs(@"C:\TempFiles\" + fileName
                                             //+ GUID 
                                             + "");
            }
        }
        catch (Exception ex)
        {
            ...
        }
}

Here I save some file in another domain, but you can check code to get how make authorization for it.

0
developernader On

Thanks it's Work. iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);

0
deadlydog On

Was getting the exact same error message, but unfortunately Yurii Maksimov's solution did not work for me; LogonUser always returned false no matter what I tried.

However, I did find this answer on a different Stack Overflow question which did the trick and allowed me to access files on my NAS via UNC paths that required credentials.

Posting this in case others come across this question and run into the same problem that I did.

2
UsernameNotFoundException On

If you're like me, and you're running a program that has worked before, but currently isn't, make sure you are not also like me and running Visual Studio, or the program itself, as Administrator. I forgot I had my Visual Studio ran as Administrator, hit Run to start debugging, and received this error as a result of the Admin being used to access a network drive, rather than my user who's domain group has access.