FJam
FJam

Reputation: 756

C# does not run or delete file

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)
 }

Upvotes: 2

Views: 285

Answers (2)

David Heffernan
David Heffernan

Reputation: 612954

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.

Upvotes: 6

Grant Thomas
Grant Thomas

Reputation: 45083

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.

Upvotes: 4

Related Questions