IF statement - Copy exe file and install

  • Thread starter Thread starter ThatSameer
  • Start date Start date
T

ThatSameer

Guest
Hi.

Hope you are all well.

I am fairly new to C#. I have some experience with PowerShell.

I am trying to understand how to do something from a PowerShell perspective so any help will be appreciated.

I would like to do 2 things in C#.

1) Do an if statement on copying an item whether it was successful or not appending to a textbox of the status

2) The same but with installing an .exe file


This is how I have done it in PowerShell and it works how I want it to:

if ($chk7Zip.Checked){

#Copy 7-Zip Install files
$rtxOutput.AppendText("Copying 7-Zip to temp local drive...`n")
$copy7zip = Copy-Item -Path "$source7ZipPath\7zip.exe" -Destination "$local7ZipPath" -PassThru

if ($copy7Zip){

$rtxOutput.AppendText("7-Zip has copied sucessfully`n");

}
else {

$rtxOutput.AppendText("7-Zip failed to copy to local drive`n");

}

#Install 7-Zip
$rtxOutput.AppendText("Installing 7-Zip...`n")
$prc7Zip = Start-Process -FilePath "$local7ZipPath\7zip.exe" -ArgumentList "/S" -PassThru -wait

if ($prc7Zip.ExitCode -eq 0){

$rtxOutput.AppendText("7-Zip installed successfully`n")

}
else{

$rtxOutput.AppendText("7-Zip failed to install`n")

}


}


This is how I have done it in C# but some things are wrong which I will mention below it:

if (chk7Zip.Checked)
{
//Create install path variables
string source7ZipPath = Path.Combine(sourceInstallPath, "7Zip.exe");
string local7ZipPath = Path.Combine(localInstallPath, "7Zip.exe");

//Copy the install file from network share to local dirve
rtxOutput.AppendText("Copying 7-Zip to temp local drive...\n");
try
{
File.Copy(source7ZipPath, local7ZipPath, true);
rtxOutput.AppendText("7-Zip has copied sucessfully\n");

//Install the file from local drive
rtxOutput.AppendText("Installing 7-Zip...\n");

try
{
Process prc7Zip = new Process();
prc7Zip.StartInfo.FileName = local7ZipPath;
prc7Zip.StartInfo.Arguments = "/S";
prc7Zip.Start();
rtxOutput.AppendText("7-Zip installed successfully\n");
}
catch
{
rtxOutput.AppendText("7-Zip failed to install\n");
}

}
catch
{
rtxOutput.AppendText("7-Zip failed to copy to local drive\n");
}

}


The issue with my C# code is the text does not append to the richtextbox until it has finished doing the processes, whereas in the PowerShell script it will append the line first then do the task.

Also, I don't believe my install success is set properly in the C# try block as it seems to think a success is the prc7Zip.Start() starting, instead of the software actually installing with error code 0 (I might be wrong).

I have done my fair bit of research and haven't come across an answer for this hence why I am now asking on here.

Ultimately I am asking how can I rewrite my PowerShell block in C# (so that it appends the text first and then does the process)

Thanks.

Continue reading...
 
Back
Top