简体   繁体   English

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

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

I developing program witch have to write some data in file whom are stored in network computer witch are protected by password. 我开发的程序必须将一些数据写入文件,这些数据存储在网络计算机中并受密码保护。 Now I'm doing this way - open connection with cmd then write data. 现在,我正在这样做-用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){ }

I believe there must by better way. 我相信必须以更好的方式。 I mean the .NET way. 我的意思是.NET方式。 Does anybody know how to do it? 有人知道怎么做吗? :) :)
Thanks 谢谢

You should store a hashed and salted password in a config file and read the value in from config before you use it in your code. 您应该在配置文件中存储哈希密码和加盐密码,并在配置代码中使用它之前从config中读取值。 There are plenty of references on how to do that on here so just do a search. 关于如何执行此操作的参考文献很多,因此只需进行搜索即可。

Try Impersonation. 尝试模拟。 You need to get access to this api 您需要访问此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);

Then using the username / password impersonate the user with the required credentials and access the network. 然后使用用户名/密码模拟用户所需的凭据并访问网络。

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 ....
}         

Thanks to and code taken from this blog 感谢并从此博客中获取了代码

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

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