Berkin
Berkin

Reputation: 1654

File not found error in C#

I have some interesting error in C# while reading a TXT file after a process ran. This process run some operations and after it finishes, copy its output to a TXT file. This txt file shown below as output.txt.

When I'm trying to run it it throws an error called file not found. But if I try to debug it with pressing F10 file can be found and everything works fine.

I guess that problem occurs when code runs while process working in the background. Code requires txt file but process still working. And error thrown.

Here its my code.

var aprioriProcess = new ProcessStartInfo();
aprioriProcess.UseShellExecute = true;

string supportValue = T_minSupport.Text;
string workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
string outputFile = "output.txt";

int index = workingDirectory.IndexOf("bin");

if (index > 0)
{
    workingDirectory = workingDirectory.Remove(index, 10);
}

if (File.Exists(workingDirectory + "/output.txt"))
{
    File.Delete(workingDirectory + "/output.txt");
}

//proc1.WorkingDirectory = @"C:\Users\berki\Documents\Visual Studio 2017\Projects\DataMining\DataMining";
aprioriProcess.WorkingDirectory = workingDirectory;
aprioriProcess.FileName = @"C:\Windows\System32\cmd.exe";

string command = "-s" + supportValue + " census.dat - >> " + outputFile;
aprioriProcess.Arguments = "/c apriori.exe " + command;

Process.Start(aprioriProcess);

string fileName = outputFile;
fileReader.ReadFile(workingDirectory + fileName);
aprioriLines = fileReader.GetEntries().Cast<AprioriOutput>().ToList();

Maybe not deleting it but updating that txt file will solve my problem but im not sure.

Thanks

Upvotes: 1

Views: 1347

Answers (2)

bornfromanegg
bornfromanegg

Reputation: 2918

You’re not waiting for the process to end, as I think you have realised. You need to store the result from Process.Start and wait for it to exit:

var process = Process.Start(aprioriProcess);

process.WaitForExit();

For further info, check here.

Upvotes: 4

Savas Alp
Savas Alp

Reputation: 194

Start() method starts the process, but doesn't wait for finish. So the file is -probably- not ready at the ReadFile() line.

Process p = Process.Start(aprioriProcess);
p.WaitForExit();

Upvotes: 1

Related Questions