当c#执行时,在系统上移动目录

本文关键字:移动 系统 执行 | 更新日期: 2023-09-27 18:04:20

我正在寻找移动我的c#应用程序。exe时运行,让我们说…文件,然后从执行位置删除。

例如,如果我在运行程序之前在桌面上运行我的。exe,将其自身复制到目录"documents",然后在文档中运行新目录后从执行目录(在我的情况下是desktop)中删除一个。

进程:运行>移动到C://Documents> Start . exe in Documents>从执行目录中删除。exe

很抱歉,如果这可能会让一些人难以理解,我尽了最大的努力来具体说明我想要完成的任务。

当c#执行时,在系统上移动目录

我希望你能这样写程序,这会对你有帮助。

1)程序i)如果程序的执行目录不是C:/Documents,检查,然后,它应该复制文件夹,并把它放在C:/Documents启动文件内的exeIi)否则获得exe及其执行目录的运行列表(如果不是C:/Documents,停止exe,并删除执行文件夹

不确定这是否有帮助,但这只是我的想法

没有办法在一个进程中做到这一点,因为你想要移动的exe将在内存中运行。

你可以让应用程序复制自己,执行复制,然后终止自己。

这肯定需要调整,是非常基本的,但希望能给你一些想法。抱歉,控制台应用程序中所有的方法都是静态的,所有的方法都应该在它们自己合适的类中。

using System;
using System.Globalization;
using System.IO;
using System.Linq;
namespace StackExchangeSelfMovingExe
{
    class Program
    {
        static void Main(string[] args)
        {
            // check if we are running in the correct path or not?
            bool DoMoveExe = !IsRunningInDocuments();
                        string runningPath = Directory.GetCurrentDirectory();
            if (DoMoveExe)
            {
                // if we get here then we are not, copy our app to the right place.
                string newAppPath = GetDesiredExePath();
                CopyFolder(runningPath, newAppPath);
                CreateToDeleteMessage(newAppPath, runningPath); // leave a message so new process can delete the old app path
                // start the application running in the right directory.
                string newExePath = $"{GetDesiredExePath()}''{System.AppDomain.CurrentDomain.FriendlyName}";
                ExecuteExe(newExePath);
                // kill our own process since a new one is now running in the right place.
                KillMyself();
            }
            else
            {
                // if we get here then we are running in the right place. check if we need to delete the old exe before we ended up here.
                string toDeleteMessagePath = $"{runningPath}''CopiedFromMessage.txt";
                if (File.Exists(toDeleteMessagePath))
                {
                    // if the file exists then we have been left a message to tell us to delete a path.
                    string pathToDelete = System.IO.File.ReadAllText(toDeleteMessagePath);
                    // kill any processes still running from the old folder.
                    KillAnyProcessesRunningFromFolder(pathToDelete);
                    Directory.Delete(pathToDelete, true);
                }
                // remove the message so next time we start, we don't try to delete it again.
                File.Delete(toDeleteMessagePath);
            }
            // do application start here since we are running in the right place.
        }

        static string GetDesiredExePath()
        {
            // this is the directory we want the app running from.
            string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            return $"{userPath}''documents''MyExe".ToLower();
        }
        static bool IsRunningInDocuments()
        {
            // returns true if we are running from within the root of the desired directory.
            string runningPath = Directory.GetCurrentDirectory();
            return runningPath.StartsWith(GetDesiredExePath());
        }
        // this copy method is from http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c-sharp
        public static void CopyFolder(string SourcePath, string DestinationPath)
        {
            if (!Directory.Exists(DestinationPath))
            {
                Directory.CreateDirectory(DestinationPath);
            }
            //Now Create all of the directories
            foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
                SearchOption.AllDirectories))
                Directory.CreateDirectory(DestinationPath + dirPath.Remove(0, SourcePath.Length));
            //Copy all the files & Replaces any files with the same name
            foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
                SearchOption.AllDirectories))
                File.Copy(newPath, DestinationPath + newPath.Remove(0, SourcePath.Length), true);
        }
        private static void CreateToDeleteMessage(string newPath, string runningPath)
        {
            // simply write a file with the folder we are in now so that this folder can be deleted later.
            using (System.IO.StreamWriter file =
            new System.IO.StreamWriter($"{newPath}''CopiedFromMessage.txt", true))
            {
                file.Write(runningPath);
            }
        }
        private static void ExecuteExe(string newExePath)
        {
            // launch the process which we just copied into documents.
            System.Diagnostics.Process.Start(newExePath);
        }
        private static void KillMyself()
        {
            // this is one way, depending if you are using console, forms, etc you can use more appropriate method to exit gracefully.
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
        private static void KillAnyProcessesRunningFromFolder(string pathToDelete)
        {
            // kill any processes still running from the path we are about to delete, just incase they hung, etc.
            var processes = System.Diagnostics.Process.GetProcesses()
                            .Where(p => p.MainModule.FileName.StartsWith(pathToDelete, true, CultureInfo.InvariantCulture));
            foreach (var proc in processes)
            {
                proc.Kill();
            }
        }
    }
}