首页 > 解决方案 > 如何以特定用户身份运行 .Net Core 进程?

问题描述

所以我试图在我的 Windows 服务器上运行一个 .exe,它需要具有特定访问权限的用户才能运行它。幸运的是,我在服务器上拥有这些权限,并且可以手动运行可执行文件。

但是,当我想从我的代码运行它时,它是一个 .net 核心控制台 API 应用程序,我遇到了一个问题:'The handle is invalid'.

这是我试图实现这一目标的方法:

public void UpdateDataSets()
        {
            try
            {
                Process processStart = new Process();

                ProcessStartInfo startInfo = new ProcessStartInfo(@"PathToExecutable.exe");
                startInfo.WindowStyle = ProcessWindowStyle.Normal;

                startInfo.Arguments = $@"MyArguments";
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow = false;
                startInfo.UseShellExecute = false;


                startInfo.UserName = "MyUserName";
                startInfo.Domain = "MyDomain";
                startInfo.Password = new NetworkCredential("", "MyUserPassword").SecurePassword;
                processStart.StartInfo = startInfo;

                string textToRead;

                using(Process process = Process.Start(startInfo))
                {
                    textToRead = process.StandardOutput.ReadToEnd();
                    process.WaitForExit(20000); //time limit because maybe infinite, I dont know?
                }

                File.WriteAllText(@"StandardOutput.txt", textToRead);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());
            }
        }

在对我的活动目录凭据进行硬编码之前,我首先尝试了使用startInfo.Verb = "runas"和使用startInfo.LoadUserProfile = true,但我在那里遇到了不同的错误。

我在这里做错了什么?

标签: c#asp.net-core-2.1

解决方案


推荐阅读