繁体   English   中英

如何以智能方式打开受密码保护的本地网络路径的连接? (使用C#)

[英]How to open connection to local network path protected by password in smart way? (Whith C#)

我开发的程序必须将一些数据写入文件,这些数据存储在网络计算机中并受密码保护。 现在,我正在这样做-用cmd打开连接,然后写入数据。

    static bool ConnectToSrv()
    {
        String myUser = "domain.local\\user";
        String myPass = "pwd";
        String cmdString = "net use \\\\otherPC\\folder\\ /user:" + myUser + " " + myPass;
        try
        {
            ManagementClass processClass = new ManagementClass("Win32_Process");
            object[] methodArgs = { cmdString, null, null, 0 };
            object result = processClass.InvokeMethod("Create", methodArgs);
            return true;
        }
        catch (System.Exception error)
        {
            return false;
        }

    }

public void writeDate(string data){ }

我相信必须以更好的方式。 我的意思是.NET方式。 有人知道怎么做吗? :)
谢谢

您应该在配置文件中存储哈希密码和加盐密码,并在配置代码中使用它之前从config中读取值。 关于如何执行此操作的参考文献很多,因此只需进行搜索即可。

尝试模拟。 您需要访问此api

// Using this api to get an accessToken of specific Windows User by its user name and password
[DllImport("advapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)]
static public extern bool LogonUser(string userName,string domain,string passWord,int logonType,int logonProvider,ref IntPtr accessToken);

然后使用用户名/密码模拟用户所需的凭据并访问网络。

private const int LOGON_TYPE_INTERACTIVE = 2;
private const int LOGON_TYPE_PROVIDER_DEFAULT = 0;

IntPtr accessToken = IntPtr.Zero;
if (LogonUser(userName,  domain, password, LOGON_TYPE_INTERACTIVE, LOGON_TYPE_PROVIDER_DEFAULT, ref accessToken))
{
   WindowsIdentity identity = new WindowsIdentity(accessToken);
   WindowsImpersonationContext context = identity.Impersonate();

   // Access network here ....
}         

感谢并从此博客中获取了代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM