简体   繁体   中英

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.

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

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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