在需要用户名/密码的网络共享上打开文件时,如何在UNC路径中传递凭据

时间:2018-11-28 12:44:30

标签: c# exe unc

我有点迷路了。 我到处搜索,但没有找到对我有意义的解决方案。

我的问题是我需要打开网络共享上的特定文件,但这给我一个例外,我的用户名或密码不正确。

我已经将UNC路径放入了一个变量:

protected internal static string demoPath846 = @"\\10.90.1.73\XMODemoer\XMO846";

然后使用此代码访问并在路径中运行文件:

File.WriteAllText(demoPath846 + @"\xmo.ini", "[system]\r\nInstanceid=846\r\nconnectionstring=" + constr846 + "\r\n[environment]\r\nA6_DRV_EDI=" + demoPath846 + "\\edi\\ \r\nA6_DRV_USER=" + demoPath846 + "\r\n\r\n[update]\r\nurl=http://10.10.62.104/xmoads/1.0 \r\ntimeout=86400000");
        string startfile846 = demoPath846 + @"\xmo.exe"; 

        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.WorkingDirectory = demoPath846;
        p.StartInfo.FileName = startfile846;
        p.Start();

1 个答案:

答案 0 :(得分:0)

您不要在路径中输入用户名或密码。你想做这样的事情...

using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
{
    if (unc.NetUseWithCredentials(uncpath, user, domain, password))
    {
        //Access your file here...
    }
    else
    {
        // The connection has failed. Use the LastError to get the system error code
        MessageBox.Show("Failed to connect to " + tbUNCPath.Text + 
                        "\r\nLastError = " + unc.LastError.ToString(),
                        "Failed to connect",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
    }
}

*示例取自Code Project