c#Program复制自身并从新位置运行

时间:2015-05-03 18:45:14

标签: c# batch-file copy

所以这是我写的一个程序的一部分。我希望程序将自己复​​制到给定的位置,写入&运行一个批处理文件,该文件终止旧进程并运行新进程。问题是它导致原始程序的无限循环被运行和杀死而不是新版本。这是我正在使用的代码。

string placementDirectory = Environment.GetFolderPath("Where I want to place the file");
string folderName = "KL";
string currentProccessDirectory = Environment.CurrentDirectory;
string currentProccessName = Process.GetCurrentProcess().ProcessName + ".exe";

if (currentProccessDirectory != placementDirectory + "\\" + folderName) //This is the check to see if it is in the correct directory
{
    if (Directory.GetDirectories(placementDirectory).Contains(placementDirectory + "\\" + folderName)) // This checks if the placement directory exists
    {
        if (Directory.GetFiles(placementDirectory + "\\" + folderName).Contains(placementDirectory + "\\" + folderName + "\\" + currentProccessName))
        {
            System.IO.File.Delete(placementDirectory + "\\" + folderName + "\\" + currentProccessName); // if the file already exists at this location, it deletes i
        }
    }
    else // if the Placement directory does not exist, it creates it
    {
        Directory.CreateDirectory(placementDirectory + "\\" + folderName);
    }
    System.IO.File.Copy(currentProccessDirectory + "\\" + currentProccessName, placementDirectory + "\\" + folderName + "\\" + currentProccessName); //Copies the running proccess to the desired location
    using (StreamWriter canWrite = new StreamWriter(placementDirectory + "\\" + folderName + "\\Copier.bat")) // Creation of the batch file to kill the and run the new proccess
    {
        canWrite.WriteLine("taskkill /f /im \"" + currentProccessName + "\"");
        canWrite.Write("START \"" + placementDirectory + "\\" + folderName + "\" " + "\"" + currentProccessName + "\"");
        canWrite.Flush();
    }
    Process.Start(placementDirectory + "\\" + folderName + "\\Copier.bat");
}

我出于某种原因,批处理文件始终打开原始可执行文件,即使它被告知要打开新的可执行文件。我不知道为什么。

2 个答案:

答案 0 :(得分:0)

通常这种类型的行为是由与exe相同名称的批处理文件引起的。因此,将exe或bat更改为复印机以外的其他内容。

答案 1 :(得分:0)

以下是在运行时在启动文件夹中复制自身的方法。

 public static void Copyitself()
    {

        string thisFile = System.AppDomain.CurrentDomain.FriendlyName;

        string Path = AppDomain.CurrentDomain.BaseDirectory + "\\" +thisFile;

            string Filepath = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + thisFile;



        try
        {

            //COPY THIS PROGRAM TO STARTUP
            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + thisFile))
            {
                System.IO.File.Copy(Application.ExecutablePath, Filepath);


            }

        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());

        }

    }