-1

我正在用 c# 制作一些 Windows 服务,我需要从配置文件中读取一些变量,比如文件和路径。我还有一个控制(它应该)定时器间隔的变量。问题是,每次更改配置文件中的数据时,都不会获取该数据,例如,如果我更改文件名,我会收到一条错误消息,指出该文件不存在(并且我检查了名称和路径) 或者如果我改变时间间隔没有任何反应。有人能帮助我吗?

System.Timers.Timer timer;
    CallWebServices call;
    int time;

    public Planview_SEB_Pervasive()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        call = new CallWebServices();
        startPervasive();
    }

    protected override void OnStop()
    {
        timer.Enabled = false;
        call.InsertLog("PV/S&B Win Service", "Serviço parado", "");
    }

    private void startPervasive()
    {
        try
        {
            try
            {
                //Vai buscar o tempo ao app.config
                time = Convert.ToInt32(ConfigurationManager.AppSettings.Get("TimeElapsedInMinutes"));
            }
            catch (Exception ex)
            {
                //Em caso de falha ficam 5 minutos
                call.InsertLog("PV/S&B Win Service StartPervasive (time)", ex.Message, "");
                time = 5;
            }
            this.timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.AutoReset = true; //Necesário para que o srviço se repita
            timer.Interval = 1000 * 60 * time; //Cálculo para minutos
            timer.Elapsed += new ElapsedEventHandler(Elapsed);
        }
        catch (Exception ex)
        {
            call.InsertLog("PV/S&B Win Service StartPervasive", ex.Message, "");
            OnStop();
        }
    }

    protected void Elapsed(Object sender, ElapsedEventArgs e)
    {
        try
        {
            timer.Interval = Convert.ToInt32(ConfigurationManager.AppSettings.Get("TimeElapsedInMinutes"));
            StartProcess();
        }
        catch (Exception ex)
        {
            call.InsertLog("PV/S&B Win Service Elapsed", ex.Message, "");
        }
    }

    private static void StartProcess()
    {
        try
        {
            string directory = ConfigurationManager.AppSettings.Get("WorkingDirectory");
            string file = ConfigurationManager.AppSettings.Get("FileToRun");


            //Execução dos processo (ficheiro)
            Process process = new Process();

            process.StartInfo.WorkingDirectory = directory;
            process.StartInfo.FileName = directory + @"\" + file;
            process.StartInfo.Arguments = "";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            process.StartInfo.CreateNoWindow = false;

            process.StartInfo.RedirectStandardOutput = false;

            process.Start();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
4

1 回答 1

0

您可以实现一个FileSystemWatcher监控 app.config 存储目录的目录。当它更新时,您将在应用程序中收到一个事件,通知您某些内容已更改。发生这种情况时,您可以重新加载 app.config 并刷新您的值。

链接:FileSystemWatcher 类

于 2012-10-17T14:06:55.170 回答