c# - 如何在C#中打开带有身份验证的文件夹?-LMLPHP如何在c#中打开带有身份验证的文件夹?
我已经使用过LogonUser了,但是没有用...

IntPtr token = IntPtr.Zero;
bool success = LogonUser("username", "domainname", "password",
    2, 0, ref token);
if (success)
{
    using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
    {
        File.Copy(sourceFileName,destFileName);

        person.Undo();
        CloseHandle(token);
    }
}


成功为真,并且我在令牌中收到一个数字,它输入if并给出用户错误和密码。


  一切正常,直到到达File.Copy部分ERROR:I
  仍然收到此错误“其他信息:登录失败:未知
  用户名或密码错误。”

最佳答案

我更改了代码并正确地为我工作,如果有人需要,我将其留在这里。



using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI.WebControls;

namespace BBVA.Canales.Front.Net.UI.WebApp.Servicios.ViewModels
{
    public class NetworkShare
    {
        [DllImport("Mpr.dll")]
        private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
            );

        [DllImport("Mpr.dll")]
        private static extern int WNetCancelConnection(
            string lpName,
            bool fForce
            );

        [StructLayout(LayoutKind.Sequential)]
        private class NETRESOURCE
        {
            public int dwScope = 0;
            public int dwType = 0;
            public int dwDisplayType = 0;
            public int dwUsage = 0;
            public string lpLocalName = "";
            public string lpRemoteName = "";
            public string lpComment = "";
            public string lpProvider = "";
        }

        const int RESOURCETYPE_DISK = 0x00000001;
        const int CONNECT_UPDATE_PROFILE = 0x00000001;


        public static void ConnectToShare(string uri, string username, string password, string idFile, HttpPostedFileBase file)
        {
            //Create netresource and point it at the share
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwType = RESOURCETYPE_DISK;
            nr.lpRemoteName = uri;

            //Create the share
            int ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

            file.SaveAs(@"\\c:\Desktop\FolderName\" + idFile);

        }

        public static void DisconnectFromShare(string uri, bool force)
        {
            //remove the share
            int ret = WNetCancelConnection(uri, force);

        }



    }
}




然后从您的代码中调用它:

 ConnectToShare("dom", @"user", @"psw", file);
  DisconnectFromShare("dom", false);

关于c# - 如何在C#中打开带有身份验证的文件夹?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52657325/

10-11 04:39