2016-08-27 2 views
0

Я ищу, чтобы переместить мое приложение C# .EXE при запуске, чтобы сказать ... Документы, а затем удалить из того места, где оно было выполнено.Переместить каталог в систему при выполнении C#?

Например, если я запустил мой .EXE на своем рабочем столе перед тем, как запустить программу, скопируйте ее в каталог «документы», а затем удалите из исполняемого каталога (который в моем случае является рабочим) после запуска нового в документы.

Процесс: Выполнить> Переместить в C: // Документы> Запустить .EXE в документах> Удалить .EXE из исполняемого каталога.

Извините, если это может показаться трудным для понимания для некоторых людей, я попытался изо всех сил указать, что я хотел выполнить.

+3

Ваш случай использования звучит так, будто вы пытаетесь написать вирус или вредоносное ПО. Какой пользователь хочет выполнить исполняемый файл из папки своих документов? –

+0

@BlackFrog может быть много причин, вирус был моим первым, хотя слишком, но это может быть много других причин, другой пример, который приходит на ум, работает в терминальной серверной среде, где системный администратор не хочет, чтобы пользователи работали с c: или где документы папка сохраняется на любом сервере в балансе нагрузки. Я мог придумать больше. –

+0

Он задал вопрос, прежде чем запускать скрытое консольное приложение, которое будет сохраняться, если консоль будет скрыта или выведена. Это кажется недобросовестным. Это также кажется очень странным «проектом» для новичка, который никогда не указывал какой-либо реальной цели для своей программы. – WakaChewbacca

ответ

0

Невозможно сделать это с помощью одного процесса, так как 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(); 
      } 
     } 
    } 
} 
+0

Отличный код, извините за то, что вы немного нооббите, но как бы поместить его в свой класс и запустить весь класс в моем Main.cs? – Austin

+0

Вы можете копировать каждый метод в другой класс, удалять статическую информацию из каждого метода, изменять основной элемент void на что-то вроде void Run. Затем в вашем основном классе создайте новый экземпляр этого класса и вызовите MyClass.Run(); –

0

Надеюсь, вы сможете написать программу таким образом, которая поможет.

1) Программа я) Проверьте если каталог выполнения программы не C:/Documents затем его следует скопировать папку и поместить его в C:/Documents и запустить ех внутри документы б) еще получить пополняемый список из ехе и их каталог выполнение (если его не C:/Documents остановить ехе и удалить папку выполнения

не уверен, если это поможет, но только это мой мысль

+0

Хорошая обратная связь Я очень ценю это. Не могли бы вы послать мне код кода, чтобы понять, что вы имеете в виду? как демо? потому что, поскольку я являюсь новичком и всем. – Austin

Смежные вопросы