tags:

views:

120

answers:

2

Hi, 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

A: 

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.

Keith
Password safety is not a problem. This is just example how I do it.
lfx
A: 

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

PaulB
It's something like that, just I always gets error - wrong user or password. (I tried program from blog)
lfx