无法重装服务

Can't reinstall service

我正在尝试为应用程序创建自动更新,但是我在更新部分遇到了一些麻烦。基本上我拥有的是一个 windows 服务,它会定期检查更新,当它发现并更新时,它会启动一个控制台应用程序来更新自己。控制台应用程序的代码如下。

我遇到的问题是,当我卸载服务并替换驱动服务的文件时,出现 system.badimageformat 异常。尽管重新安装了相同的文件。如果我卸载并重新安装文件而不下载它并从 FTP 替换它,则没有问题,但一旦我更改文件,它就会开始给我异常。有没有人对我如何解决此错误有任何想法。我相信这不是 32 位与 64 位的问题,这通常是导致此错误的原因。

    static void Main(string[] args)
    {
        if (!System.Diagnostics.EventLog.SourceExists("OCR Updater"))
        {
            EventLog.CreateEventSource("OCR Updater", "Application");
        }
        ServiceController sc = new ServiceController("OCR Scheduler", ".");
        if (sc.Status == ServiceControllerStatus.Running)
        {
            sc.Stop();
            sc.WaitForStatus(ServiceControllerStatus.Stopped);
        }

        ProcessStartInfo Uninstallpsi = new ProcessStartInfo();
        Uninstallpsi.Verb = "runas";
        Uninstallpsi.UseShellExecute = false;
        Uninstallpsi.FileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "installutil.exe";
        Uninstallpsi.Arguments = " /u " + "\"" + AppDomain.CurrentDomain.BaseDirectory.ToString() + "OCR_Scheduler_Service.exe\"";
        Process.Start(Uninstallpsi);

        Console.WriteLine("Sleeping Thread after uninstall");
        System.Threading.Thread.Sleep(10000);


        OCRUpdater program = new OCRUpdater();
        List<string> Files = program.GetFiles();
        foreach (string item in Files)
        {

            if (item.ToString() == "Sqlite" || item.ToString() == "License.xml")
            {
                continue;
            }
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.mccinnovations.com/OCR_Scheduler/V2Updates/Files/" + item);
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("ftp admin", "_Stingray_12");

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            string[] temp = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            reader.Close();
            response.Close();
            string DesktopFile = "";


            try
            {
                DesktopFile = @"C:\Users\hnelson\Desktop\" + item;
                if (File.Exists(DesktopFile))
                {
                    File.Delete(DesktopFile);   
                }
                File.WriteAllLines(DesktopFile, temp);
            }
            catch (Exception ex)
            {

                EventLog.WriteEntry("OCR Updater", "Error in file path" + DesktopFile + ex.Message);
                continue;
            }
            try
            {
                File.Delete(@"C:\Program Files (x86)\MCCi\OCR Scheduler V2\" + item);
                System.Threading.Thread.Sleep(2000);
                File.Copy(DesktopFile, @"C:\Program Files (x86)\MCCi\OCR Scheduler V2\" + item, true);
                File.Delete(DesktopFile);
                EventLog.WriteEntry("OCR Updater", DesktopFile);
            }
            catch (Exception)
            {

                EventLog.WriteEntry("OCR Updater", DesktopFile);
                EventLog.WriteEntry("OCR Updater", "Error in file path " + @"C:\Program Files (x86)\MCCi\OCR Scheduler V2\" + item);
                continue;
            }


        }




        try
        {

            System.Threading.Thread.Sleep(5000);

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.Verb = "runas";
            psi.UseShellExecute = false;
            psi.FileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "installutil.exe";
            psi.Arguments = " " + "\"" + AppDomain.CurrentDomain.BaseDirectory.ToString() + "OCR_Scheduler_Service.exe\"";
            Process.Start(psi);


        }
        catch (Exception ex)
        {

            EventLog.WriteEntry("OCR Updater", "Could not reinstall service" + ex.Message + ex.InnerException);
        }


        System.Threading.Thread.Sleep(10000);

        Console.WriteLine("Finished resinstalling the service.");


        try
        {



            string[] serviceStartArgs = { "true" };

            sc.Start(serviceStartArgs);
            sc.WaitForStatus(ServiceControllerStatus.Running);

        }
        catch (Exception ex)
        {

            EventLog.WriteEntry("OCR Updater", "Could not start the service after install" + " " + ex.Message + ex.InnerException);
        }

    }

    public List<string> GetFiles()
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.mccinnovations.com/OCR_Scheduler/V2Updates/Files/");
        request.Method = WebRequestMethods.Ftp.ListDirectory;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential("ftp admin", "_Stingray_12");

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        List<string> Files = new List<string>();
        while (reader.EndOfStream == false)
        {
            Files.Add(reader.ReadLine());
        }

        reader.Close();
        response.Close();
        return Files;


    }


}

}

主要问题是您将文件视为文本文件:

string[] temp = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
....
File.WriteAllLines(DesktopFile, temp);

您可以改用这个:

Stream responseStream = response.GetResponseStream();

...

using (FileStream destStream = File.Create(DesktopFile))
{
    responseStream.CopyTo(destStream);
}

responseStream.Close();
response.Close();

但是,这仍然不是最佳解决方案,因为您应该使用模式

using (X123 x123 = new X123(y))
{
    // do something with x123
}

对于所有支持 IDisposable 的 类。

此外,我对在这么多情况下使用 Sleep() 有一些顾虑。这很少是个好主意。