Как устранить ошибку «System.IO.IOException: неверное имя пользователя или пароль» с использованием asp.net? - PullRequest
0 голосов
/ 16 октября 2018

Я просто хочу получить имя папки, которая находится в другом домене.Я могу получить имя папки, когда пытаюсь получить имя папки локально.

Вот мой код

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

Сообщение об ошибке:

System.IO.IOException: Неверное имя пользователя или пароль.

ОБНОВЛЕНИЕ

Я попробовал этот код ниже.

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

    }

Выдает следующую ошибку

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

1 Ответ

0 голосов
/ 16 октября 2018

Я полагаю, ваш хост и целевой компьютер на базе Windows.Я делал это ранее, но мой код выглядел немного иначе.постараюсь составить какой-нибудь сценарий (в двух словах).Сначала импортируйте эту DLL.Проверьте параметры и поиграйтесь с форматированием входов.Я действительно не помню, как они должны выглядеть.

[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)
        {
            ...
        }
}

Здесь я сохраняю некоторый файл в другом домене, но вы можете проверить код, чтобы узнать, как сделать авторизацию для него.

...