Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Rewrite the following c# code, using only if statements (NO “else”). There is an

ID: 3773386 • Letter: R

Question

Rewrite the following c# code, using only if statements (NO “else”). There is an error in the file-access portion of the code. What is it, and why is that an issue?:

bool a=false,b=false;
int c=0,d=0;

<...>

if (a == true && b == false && c == 1 && d == 0)
{
StreamWriter writer1 = null;
writer1 = new StreamWriter("C:OutputWrite1.txt");
Console.SetOut(writer1);
Console.WriteLine("True");
}
else
{
StreamWriter writer2 = null;
writer2 = new StreamWriter("C:OutputWrite2.txt");
Console.SetOut(writer2);
Console.WriteLine("False");
}

Explanation / Answer

//Removed else statement from code and
//try-catch block is added to code to check if file exists or not
//If file not exist, then catch the exception

bool a=false,b=false;
int c=0,d=0;

if (a == true && b == false && c == 1 && d == 0)
{

   //Opening a file must be in a try catch block
   //If file opening has error or exception, then it caught in catch block
   try
   {

       StreamWriter writer1 = null;
       writer1 = new StreamWriter("C:OutputWrite1.txt");

      //SetOut redirect console output to the text file
       Console.SetOut(writer1);
       Console.WriteLine("True");
   }
   catch(IOException e)
   {
   Console.WriteLine(e.Message);
    }

}


//Removed else statement
//Opening a file must be in a try catch block
//If file opening has error or exception, then it caught in catch block
try
{

   StreamWriter writer2 = null;
   writer2 = new StreamWriter("C:OutputWrite2.txt");

    //SetOut redirect console output to the text file
   Console.SetOut(writer2);
   Console.WriteLine("False");
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote