0

I'm trying to make a simple exe that, when opened, moves itself to my documents folder, but when i open it, it doesn't do that, what can i do?

string fileName = "installer.exe";
string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string strWorkPath = System.IO.Path.GetDirectoryName(strExeFilePath);
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFileMove = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
System.IO.File.Move(sourceFile, destFileMove);
Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30
artapp
  • 11
  • 2
  • 2
    "it doesn't do that" - are there any errors thrown? – phuzi Dec 20 '21 at 12:12
  • 3
    "Moves itself" - When the application is running, the files for it will be locked, and prevented from being moved. So what it is you are really trying to do? – JonasH Dec 20 '21 at 12:15
  • If that's all that the program does, you'll find the reason it didn't work back in the Windows Application event log. Use the debugger to diagnose exceptions, beware of try/catch-say-nothing code. https://stackoverflow.com/a/3133249/17034 – Hans Passant Dec 20 '21 at 12:55
  • @JonasH that is incorrect. You _can_ move the current exe as that's just a rename operation. Give it a try with a simple console app and you'll see it works even while the executable is running. – julealgon Dec 20 '21 at 13:01
  • 2
    @Ortund - That's not a helpful comment. – Enigmativity Dec 20 '21 at 13:04

1 Answers1

2

File.Move(string, string) takes in 2 file names, so your second parameter is incorrect: instead of passing the target folder, you have to pass the target full file name.

If you want to preserve your previous file name, do it like this:

string destFileMove = Path.Combine( 
    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
    fileName);
julealgon
  • 7,072
  • 3
  • 32
  • 77