如何从Windows服务运行命令?

时间:2016-03-09 10:32:09

标签: c# windows-services

我写了一个C#服务程序来执行一个windows命令。它没有执行命令,但服务正常运行。任何人,请帮我解决这个问题

public partial class ScheduledService : ServiceBase
{
    Boolean armed = false;
    //Initialize the timer
    //This method is used to raise event during start of service
    Timer timer = new Timer();

    public ScheduledService()
    {
        InitializeComponent();
    }        

    protected override void OnStart(string[] args)
    {
        //add this line to text file during start of service
        TraceService("start service");

        //handle Elapsed event
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

        //This statement is used to set interval to 1 minute (= 60,000 milliseconds)

        timer.Interval = 10000;
    }


    //This method is used to stop the service
    protected override void OnStop()
    {
        timer.Enabled = false;
        TraceService("stopping service");
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        ExecuteCommandSync("echo.|clip");
        TraceService("Another entry at "+DateTime.Now);
        System.Windows.Forms.Clipboard.Clear();                
    }

    private void TraceService(string content)
    {
        //set up a filestream
        FileStream fs = new FileStream(@"d:\ScheduledService.txt",FileMode.OpenOrCreate, FileAccess.Write);

        //set up a streamwriter for adding text
        StreamWriter sw = new StreamWriter(fs);

        //find the end of the underlying filestream
        sw.BaseStream.Seek(0, SeekOrigin.End);

        //add the text
        sw.WriteLine(content);
        //add the text to the underlying filestream

        sw.Flush();

        //close the writer
        sw.Close();
    }

    public void ExecuteCommandSync(object command)
    {
        try
        {
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.CreateNoWindow = true;
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();
        }
        catch (Exception objException)
        {
            // Log the exception
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你每隔10秒就调用一次OnElapsedTime,但除了LogTracing之外没有在这个函数中做任何事情。我想你想从OnElapsedTime调用ExecuteCommandSync来运行命令。