0

I'm looking to move my C# application .EXE when ran to lets say... Documents and then delete from the place which it was executed.

For example, If I ran my .EXE on my desktop before running the program copy itself to the directory "documents" and then delete the one from executed directory (which in my case is desktop) after running the new one in documents.

Process: Run > Move to C://Documents > Start .EXE in documents > Delete the .EXE from the executed directory.

Sorry if this may come across hard to understand for some people I tried my best to specifically state what I wanted to accomplish.

Austin
  • 3
  • 1
  • 3
    Your use-case sounds likes you are trying to write a virus or malware. Which user wants a executable running from their documents folder? – Black Frog Aug 27 '16 at 04:20
  • @BlackFrog could be many reasons, virus was my first though too but it could be many other reasons, another example which comes to mind is running in a terminal server environment where system admin doesn't want users running from c: or where documents folder persists across any server in a load balance. I could think of more. – Joe_DM Aug 27 '16 at 04:58
  • He has asked a question before about running a hidden console application that would persist if the console were hidden or exited. This seems like ill-intent. This also seems like a very odd "project" for a beginner who has never stated any actual purpose for his program. – WakaChewbacca Aug 27 '16 at 05:09
  • I'm making a parental program. Not a virus. Coding a virus in .Net framework is useless. – Austin Aug 27 '16 at 05:36

2 Answers2

1

I hope you can write the program in this way which will help.

1) program i) Check if the program's execution directory is not C:/Documents then it should copy the folder and put it in C:/Documents and start the exe inside the documents ii) else get a running list of the exe and their execution directory (if its not C:/Documents stop the exe, and delete the execution folder

not sure if this will help , but just this is my thought

manas dash
  • 310
  • 1
  • 8
  • Nice feedback I really appreciate it. Could you maybe send me a sliver of code to understand what you mean? as a demo? because as me being a beginner and all. – Austin Aug 27 '16 at 04:05
0

There's no way to do this with a single process as the exe which you want to move is going to be running in memory.

You could make the application copy itself, execute the copy, then kill itself.

this will definitely need to be tweaked and is very basic, but hopefully will give you some idea. sorry that it's all statics in a console application, all the methods should be in their own appropriate class.

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();
            }
        }
    }
}
Joe_DM
  • 985
  • 1
  • 5
  • 12
  • Great code, sorry for being a bit noobish but how would I put this into its own class and run the whole class in my Main.cs? – Austin Aug 27 '16 at 05:28
  • You could copy every method into another class, remove the static from every method, change the void main to something like void Run. Then in your main class create a new instance of this class and call MyClass.Run(); – Joe_DM Aug 27 '16 at 05:33