从Windows服务C#开始的新进程的安全上下文

时间:2013-01-15 16:55:45

标签: c# windows multithreading service process

我有一个在登录时运行的Windows服务“UserA”。 Windows服务的工作是在计时器已用事件上启动新进程。

private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Task.Factory.StartNew(() => StartNewProcess());
}

private void Initialize()
{
    newProcess = new Process();
    newProcess.StartInfo.FileName = "Test.exe";
    newProcess.StartInfo.Arguments = "sessionId...";
    newProcess.StartInfo.CreateNoWindow = false;
    newProcess.StartInfo.ErrorDialog = false;
    newProcess.StartInfo.RedirectStandardError = true;
    newProcess.StartInfo.RedirectStandardInput = true;
    newProcess.StartInfo.UseShellExecute = false;
    newProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;            
}

private void StartNewProcess()
{
    newProcess.Start();
}

在任务管理器上,我看到Windows服务和新进程都将“用户名”作为“UserA”。

但问题是Windows服务能够访问“C:\ QueryResult”但新进程无法访问“C:\ QueryResult”

我在进程

上使用File.Copy("C:\QueryResult", "D:\blahblah")

新流程中的安全上下文是否已更改?

1 个答案:

答案 0 :(得分:0)

尝试自动升级应用程序权限,如下所示:

using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Windows.Forms;

public static class Program
{
    [STAThread]
    public static void Main()
    {
        if (!IsAdmin() && IsWindowsVistaOrHigher())
            RestartElevated();
        else
            DoStuff();
    }

    private static Boolean IsAdmin()
    {
        WindowsIdentity identity = WindowsIdentity.GetCurrent();

        if (identity != null)
            return (new WindowsPrincipal(identity)).IsInRole(WindowsBuiltInRole.Administrator);

        return false;
    }

    private static Boolean IsWindowsVistaOrHigher()
    {
        OperatingSystem os = Environment.OSVersion;
        return ((os.Platform == PlatformID.Win32NT) && (os.Version.Major >= 6));
    }

    private static void RestartElevated()
    {
        String[] argumentsArray = Environment.GetCommandLineArgs();
        String argumentsLine = String.Empty;

        for (Int32 i = 1; i < argumentsArray.Length; ++i)
            argumentsLine += "\"" + argumentsArray[i] + "\" ";

        ProcessStartInfo info = new ProcessStartInfo();

        info.Arguments = argumentsLine.TrimEnd();
        info.CreateNoWindow = false;
        info.ErrorDialog = false;
        info.FileName = Application.ExecutablePath;
        info.RedirectStandardError = true;
        info.RedirectStandardInput = true;
        info.UseShellExecute = false;
        info.Verb = "runas";
        info.WindowStyle = ProcessWindowStyle.Hidden; 
        info.WorkingDirectory = Environment.CurrentDirectory;

        try
        {
            Process.Start(info);
        }
        catch { return; }

        Application.Exit();
    }
}