1

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

Liam neesan
  • 2,282
  • 6
  • 33
  • 72
  • 1
    Possible duplicate of [How to provide user name and password when connecting to a network share](https://stackoverflow.com/questions/295538/how-to-provide-user-name-and-password-when-connecting-to-a-network-share) – Uwe Keim Oct 16 '18 at 09:09
  • @UweKeim I am trying [this](https://social.msdn.microsoft.com/Forums/vstudio/en-US/287ca606-86da-4794-baed-2ad5db9bc833/access-to-remote-folder?forum=netfxbcl) one – Liam neesan Oct 16 '18 at 09:13
  • @UweKeim then What is the use of `NetworkCredential`? – Liam neesan Oct 16 '18 at 09:17
  • May I know Why I get the negative vote? – Liam neesan Oct 16 '18 at 09:19

4 Answers4

2

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.

Yurii Maksimov
  • 134
  • 1
  • 5
  • [Impersonation](https://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User) is something different than [using network credentials to a access an UNC location](https://stackoverflow.com/a/295703/107625). – Uwe Keim Oct 16 '18 at 09:05
  • 1
    BTW: This empty catch phrase is horrible. Not even suitable for an example code. Better leave out all premature exception handling than providing an errorneous one. – Uwe Keim Oct 16 '18 at 09:09
  • Sure, impersonation and access to unc location are different things but could give some ideas for author's needs. Ahha, agreed about an exception handling but it's enough for example and doesn't claim for any real using :) – Yurii Maksimov Oct 16 '18 at 09:16
  • @Liamneesan Yes, I see your update. 1. Your account (USerName/password) should have access to your target host. Be sure about this; 2. try to play with username format, I do not remember exactly what it should be. Maybe with domainName DomainName\\UserName – Yurii Maksimov Oct 16 '18 at 11:03
  • @IuriiMaksimov I gave my `Domain\\Username and Password`. but still not – Liam neesan Oct 16 '18 at 11:10
  • @Liamneesan Try to use the admin/system account. Check AD permissions as well Uwe Keim says right, impersonation and unc access are two different things. If you have AD and admin user, your target host in local network, it should work. If your try just get access to some path play with link his gave you. – Yurii Maksimov Oct 16 '18 at 11:18
  • @IuriiMaksimov I am trying to access `192.168.x.x\c$\Folder1\Folder2`.. this is my path – Liam neesan Oct 16 '18 at 11:38
0

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.

deadlydog
  • 22,611
  • 14
  • 112
  • 118
-1

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

developernader
  • 105
  • 1
  • 4
-1

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.

  • This seems to be a comment – Lajos Arpad Mar 24 '23 at 16:04
  • @LajosArpad https://stackoverflow.com/help/how-to-answer "So long as you fully answer at least a part of the original question, then you can contribute the results of your research and anything additional you’ve tried. That way, even if you can’t figure it out, the next person has more to go on." - I was directly responding to the OP with a solution that worked to solve an almost identical problem. Thank you for your concern. – UsernameNotFoundException Mar 27 '23 at 14:28