Unzip files in C# (using winzip command line) - c#

I'm trying to create program to unzip files. I need to use winzip command line. I try to send in argument command to cmd, but it didn't work, because cmd didn't know my command. When I pasted manually command, it works.
var process = new ProcessStartInfo("cmd.exe");
var command = "/c WZUNZIP -spassword" + "\""+ "C:\my path\file.zip" + "\"" + " " + "\"" + "C:\my path" + "\"";
process.UseShellExecute = false;
process.Arguments = command;
Process.Start(process);
I tried to create .bat file and execute this file in my program, but like before it didn't work, when I executed it in my program and when start manually it works.
start cmd.exe /c WZUNZIP -spassword "C:\my path\file.zip" "C:\my path"
var process = new ProcessStartInfo("cmd.exe", pathToBatch);
Process.Start(process);
Mayby u know, the best way to execute .bat file in C#.
I need to use winzip, because only it provides encoding for my files. I tried to use DotNetZip and during uziping program threw exception that it can't be unziped, because library can't operate this files.

Apologies for adding as an answer (I currrently don't have enough rep for posting comments), but hopefully this will help.
What is the reason that you need to use winzip command line? Could you use ionic zip instead (http://dotnetzip.codeplex.com/ - also obtainable via NuGet in Visual Studio). I've used it a few times to zip files up and I know it unzips just as well.
The benefit I can see of not using the winzip command line is that you don't get the command prompt window popping up onscreen while the unzip is in progress.
Otherwise, as Noodles has suggested, the quotes must go around the whole path, not just the folders containing the spaces.
Edit: There is a similar SO post here: unzip file in C# via Winzip and its cmd extension

If you want to execute any thing you can use the process class with ProcessStartInfo.Arguments.
You can see more at:
MSDN: Process Class
MSDN: ProccessStartInfo.Arguments Property
And my question is because I don't understand for what you want it,
why don't you use system.IO.Compression or SharpzipLib? You can look up more info and download it with nugget.

Quotes go aroundthe entire path incl drive letter "c:\some folder\some file.zip"
To unzip
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set DestFldr=objShell.NameSpace(Ag(1))
Set SrcFldr=objShell.NameSpace(Ag(0))
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Msgbox "Finished"
and to zip
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(Ag(1))
Set DestFldr=objShell.NameSpace(Ag(0))
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Msgbox "Finished"
and create a blank zip.
Set Ag=Wscript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(Ag(0), 8, vbtrue)
BlankZip = "PK" & Chr(5) & Chr(6)
For x = 0 to 17
BlankZip = BlankZip & Chr(0)
Next
ts.Write BlankZip

Here's what works for me:
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", #"/c WZUNZIP.EXE -ye -o " + zipPath + " " + ExtractedFilesLocation);
procStartInfo.UseShellExecute = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();

Related

Why doesn't my argument pass to CMD in Windows Forms app?

This is my first Windows forms app.
I'm trying to pick a folder and list all files in that folder to a txt file.
This just instantly close the console window without passing the arguments.
If I put it in a bat file it works like it should.
Any ideas?
myPath = fbd.SelectedPath;
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.Arguments = "/K for /r " + myPath + " %%g in (*) do echo %%~ng >> " + myPath + "test.txt";
p.StartInfo = psi;
p.Start();
Put the whole /k or /c command in quotes [*]. Use quotes around the file paths in case they contain spaces. And don't double the percent in the %g loop variable. That's only required in batch files. For example:
"/k \"for /r \"" + myPath + "\" %g in (*) do echo %~ng >> \"" + myPath + "\\test.txt\"\""
[*] Quoting the entire command isn't necessary in this case because the first character of the command isn't a quote. However, it's a good practice in general since cmd strips off the first and last quote if a command starts with a quote. This breaks a command such as "C:\\some path\\command.exe" "C:\\another path\\file.ext", which cmd would execute as C:\some path\command.exe" "C:\another path\file.ext.
why you are not directly running your .bat file ?
save whatever you want your application to do on a .bat file place it in the "bin" folder of your application, then add a namespace using system.diagonostics ; and generate and event like form load or button click and then write the following code process.start("name of your .bat file")

forcing to close a file

I have file that another process using it.
and I want to force closing the file. so that I will work on the fill.
I tried to use Handle.exe however it didn't find the process
would appreiciate some help here is my code:
Process tool = new Process();
tool.StartInfo.FileName = handlPath;
tool.StartInfo.Arguments = _pathDirectory + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
I'm sure, that if a program really holds an exclusive access to a file, it has a reason to do it. For example, Windows Explorer holds it when the file is in copying process.
Very often, programs open a file for a writing, but do not actively write to it. For example, when you open a document in MS Word, it is copied to the temp file and a source file is just "open for writing". You'll still have an exception if you use standard File.Open method, but you can copy it to a temp file using File.Copy.
Alternatively, you can explicitly specify FileShare.ReadWrite parameter and get an access to a file. In this case, other program will have problems with accessing a file.
If you have mentioned the file name or type it would have been more easier, anyway try using the cmd for this. Get the process name and replace ProcessName.exe of the following code.
First you'll have to add using System.Diagnostics; on top.
Process.Start("cmd.exe", "/c taskkill /F /IM ProcessName.exe");

Create and run a batch file containing special chars as accent

I am actualy creating a batch file from my C# application. (path contains accents for example)
using (System.IO.StreamWriter file = new System.IO.StreamWriter("file.bat", false))
{
var path = "C:\directory_été";
var whoot = #"#echo off" + Environment.NewLine + #"pushd %~dp0" + Environment.NewLine + path; // where path contains accents and such
file.Write(whoot);
}
When opening the .bat file with notepad.exe, everything looks written perfectly.
Then my app is running the batch.
var Info = new ProcessStartInfo();
Info.Arguments = "/C choice /C Y /N /D Y /T 3 & start /b \"myBatchTitle\" \"C:\\file.bat\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
The batch returns an error because it is not finding the "path" because it changed the accents into some garbage characters.
So, everything looks ok in the .bat itself, but when running it, it fails reading correctly cause of the encoding.(path echoed as "directory_ÚtÚ" when batch is ran, i cant even copy the Ú from cmd prompt cause its printed correctly here then lol)
How can i fix this please? (and not MANUALLY change characters one by one)
Or isn't there a way to encode the string in C# to OEM something so it will be reading correctly? (example change é to Ú already, for ALL characters)
(For more infos, the created batch file is running 7zip command line version, and the path i submit to it is containing the accents and such)
Otherway, do you know any portable-command-line alternative, accepting real UTF8 encoding so ll languages will be accepted?
I don't know what the appropriate code page is for C:\directory_été (maybe you do, since you are dealing with this file). You can try codepage 863, which is for Canadian French.
In any case, if you know the codepage, you could try changing code page via chchp xxx where xxx is the number identifying the code page you want to switch to. So you could try chcp 863. You can put this in your batch file before you use the path with the accents.

Executing excel from C# Application

I want to open a file from a Class in C# using a Process, located in a directoy I asked the user.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "EXCEL.EXE";
startInfo.Arguments = Here goes the directory I asked
Process.Start(startInfo);
The problem, is that when the location of the file indicated by the user has an space," ", excel thinks that I'm sending two sepparate locations. For example with C:\Users\dj\Desktop\da ba excel tries to open " C:\Users\dj\Desktop\da" as one file, and at the same time "ba" as another file. How can I send a location to excel which has an space, without having this error? with an addres like C:\Users\dj\Desktop\daba without an space it works perfectly.
Try quoting your path:
startInfo.Arguments = "\"" + "C:\Users\dj\Desktop\da ba.xls" + "\"";
Tim
Try using a string literal
startInfo.Arguments = #"C:\Users\un\Desktop\file with space"
This way works
"\"" + #dialog.FileName + "\"";

Open a pdf file programmatically at a named destination

I would like to open a PDF file at named destination using WinForms (C#). Here is my code:
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "Acrobat.exe";
myProcess.StartInfo.Arguments = "/A \"nameddest=Test2=OpenActions\" C:\\example.pdf";
myProcess.Start();
It always opens the file at page 1 even having the destination Test2 at page # 10. It basically ignores the destination parameter. However if I use another parameter like the page number it works fine. For example:
myProcess.StartInfo.Arguments = "/A \"page=5=OpenActions\" C:\\example.pdf";
will always open the PDF document at page 5.
Thanks in advance for your help
I use the following code:
string strNamedDestination = "MyNamedDestination"; // Must be defined in PDF file.
string strFilePath = "MyFilePath.pdf";
string strParams = " /n /A \"pagemode=bookmarks&nameddest=" + strNamedDestination + "\" \"" + strFilePath + "\"";
Process.Start("AcroRd32.exe", strParams);
Note the "/n" inside the params. It makes Adobe to always open a new document. Otherwise, if the document was already opened, it doesn't move it to the right Named Destination. It depends on the behaviour you want for your application.
Regarding the Adobe documentation when opening a PDF document from a command shell, you can pass the parameters to the open command using the /A switch using the following syntax:
myProcess.StartInfo.Arguments = "/A \"nameddest=Test2=OpenActions\" C:\\example.pdf";
If I omit the OpenActions parameter everything works fine like:
myProcess.StartInfo.Arguments = "/A \"nameddest=Test2\" C:\\example.pdf";
I'm not sure why the OpenActions breaks opening the file but with omitting it works fine.
I have a csv with 5 columns.
Column1 contains PDF names and Column5 pagenumbers.
The executable displays the csv.
When I doubleclick on a line in the csv the following code is executed :
ListViewItem item = lvwItems.SelectedItems[0];
Process myProcess = new Process();
myProcess.StartInfo.FileName = "Acrobat.exe";
myProcess.StartInfo.Arguments = "/A page=" + item.SubItems[4].Text + " " + item.Text;
myProcess.Start();
This opens the selected PDF which name is in item.Text on the page which pagenumber is in item.SubItems[4].Text
Have you set up the destinations? You need to be have the standard or professional versions of Adobe Acrobat in order to do this:
http://kb2.adobe.com/cps/317/317300.html
Adobe Reader has a few bugs regarding opening to named destinations. Take a look at http://xenon.arcticus.com/open-pdf-named-destination-dde-c-c for some information and workarounds.

Categories