【问题标题】:Error while executing xcopy from C# code as different user以不同用户身份从 C# 代码执行 xcopy 时出错
【发布时间】:2015-02-06 01:58:50
【问题描述】:

我正在编写一个小程序来将文件从一台服务器复制到另一台服务器,为此我使用 C# 代码中的xcopy 命令。我想以不同的用户身份执行该过程,我正在使用以下代码 -

string sourceLoc = @"c:\test\xyz.xlsx";

string destinationLoc = @"c:\subfolder";

var abc= "Password";
var pass = new System.Security.SecureString();

foreach (char c in abc)
{
    pass.AppendChar(c);
}

// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UserName = "admin";
startInfo.Password = pass;
startInfo.Domain = "domain";
startInfo.Verb = "runas";
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;


startInfo.FileName = "xcopy";

startInfo.WindowStyle = ProcessWindowStyle.Hidden;

startInfo.Arguments = "\"" + sourceLoc + "\"" + " " + "\"" + destinationLoc + "\"" + @" /e /y /I";

try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch (Exception exp)
{
throw exp;
}

但我收到以下错误:-

未处理的异常:System.ComponentModel.Win32Exception:目录名称无效 在 C:\Users\sdg\documents\visual studio 2010\Projects\LogReader\LogReader\Program.cs:line 66 中的 LogReader.Program.Main(String[] args) 处

如果我在不提供其他用户凭据的情况下运行程序,它可以正常工作。

【问题讨论】:

  • 您启动它的用户是管理员吗?因为你不能在没有管理员身份的情况下以管理员身份从 C# 运行程序(想象一下其中的安全漏洞)
  • @icemanind ,感谢您的回复,不,它不是管理员,这是否会导致问题,因为我使用模拟用户使用相同的用户凭据获取正在运行的服务状态。

标签: c# xcopy processstartinfo


【解决方案1】:

我没有复制您的环境,所以这只是一个想法,但我已经能够通过将ProcessStartInfo.WorkingDirectory 设置为当前用户无权访问的文件夹来复制此错误。如果它默认为当前应用程序的工作文件夹,它可能会尝试使用c:\Users\ 下的路径,而其他用户无权访问。

【讨论】:

  • 感谢您的回复兄弟,是的,您是对的,问题在于当前应用程序工作目录的权限,我通过将 ProcessStartInfo.WorkingDirectory 值设置为另一个文件夹来解决它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 2013-10-03
  • 2020-08-01
相关资源
最近更新 更多