This C# program makes a batch file runs it and then is supposed to delete the file. When I run the program it makes the batch file and executes it perfectly if the last if statement is not there. But with the last if statement it makes the file and deletes it but does not make any changes.
string batFile;
batFile = genBat(textBox1.Text);
string path = "C:\\Windows\\System32\\drivers\\etc\\blocksite.bat";
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(@batFile);
sw.Close();
}
Process.Start(path);
if(File.Exists(path))
{
File.Delete(path)
}
Probably what happens is that you are managing to delete the .bat file before the cmd.exe process can read and process it. You'll need to wait for the process that you start with Process.Start to finish before deleting the file. Like this:
using (var process = Process.Start(path)) {
process.WaitForExit();
}
As an aside, I do wonder why you feel the need to create the .bat file in a directory where you are not supposed to write. You could readily create the .bat file under the temporary directory. If you need the working directory to be a different directory then you can readily specify that when starting the process.
There's a good chance you're deleting the file before the process has actually started processing. You should store the Process returned by Process.Start (as a general rule, you should never just neglect the returned result of an operation in .NET) and use WaitForExit, and then delete the file.
using (var process = Process.Start(path)) {
process.WaitForExit();
}
Remembering that a Process is a disposable thing, it's an even worse idea to neglect the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With