I'm trying to unzip a file from a winform application.
I'm using this code :
string dezarhiverPath = #AppDomain.CurrentDomain.BaseDirectory + "\\7z.exe";
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = dezarhiverPath;
pro.Arguments = #" e c:\TEST.ZIP";
Process x = Process.Start(pro);
x.WaitForExit();
The code doesn't return error but doesn't anything.
I tried this command also from cmd :
K:\>"C:\Test\7z.exe" e "c:\TEST.ZIP"
but in cmd ,I receive this error message :
7-Zip cannot find the code that works with archives.
Can somebody help me to unzip some files from c# ?
Thanks!
Why would you bother trying to use the 7z.exe application externally? That is a very kludgy way of doing it. Instead use one of the many libraries at your disposal.
If this is a new application, and you are targeting .NET 4.5, The new System.IO.Compression namespace has a ZipFile class.
Alternatively, SharpZipLib is a GPL library for file compression in .NET. There are online samples.
Also available is DotNetZip which is Ms-PL licensed.
Hey use this code below , you must have 7zip application in your system .
public void ExtractFile(string source, string destination)
{
string zPath = #"C:\Program Files\7-Zip\7zG.exe";// change the path and give yours
try
{
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex) {
//DO logic here
}
}
to create :
public void CreateZip()
{
string sourceName = #"d:\a\example.txt";
string targetName = #"d:\a\123.zip";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"C:\Program Files\7-Zip\7zG.exe";
p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
Refer Following Code:
using System.IO.Compression;
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
Referance Link:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/849c4969-24b1-4650-88a5-5169727e527f/
You can use SevenZipSharp library
using (var input = File.OpenRead(lstFiles[0]))
{
using (var ds = new SevenZipExtractor(input))
{
//ds.ExtractionFinished += DsOnExtractionFinished;
var mem = new MemoryStream();
ds.ExtractFile(0, mem);
using (var sr = new StreamReader(mem))
{
var iCount = 0;
String line;
mem.Position = 0;
while ((line = sr.ReadLine()) != null && iCount < 100)
{
iCount++;
LstOutput.Items.Add(line);
}
}
}
}
Try this
string fileZip = #"c:\example\result.zip";
string fileZipPathExtactx= #"c:\example\";
ProcessStartInfo p = new ProcessStartInfo();
p.WindowStyle = ProcessWindowStyle.Hidden;
p.FileName = dezarhiverPath ;
p.Arguments = "x \"" + fileZip + "\" -o" + fileZipPathExtact;
Process x = Process.Start(p);
x.WaitForExit();
This maybe can help you.
//You must create an empty folder to remove.
string tempDirectoryPath = #"C:\Users\HOPE\Desktop\Test Folder\zipfolder";
string zipFilePath = #"C:\Users\HOPE\Desktop\7za920.zip";
Directory.CreateDirectory(tempDirectoryPath);
ZipFile.ExtractToDirectory(zipFilePath, tempDirectoryPath);
Related
I am making a program that seeks out secured PDFs in a folder and converting them to PNG files using ImageMagick. Below is my code.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose();
if(PDFCheck)
{
//do nothing
}
else
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
ProcessStartInfo startInfo = new ProcessStartInfo(#"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe");
startInfo.Arguments = arguments;
Process.Start(startInfo);
}
}
}
I have ran the raw command in command prompt and it worked so the command isn't the issue. Sample command below
"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.PDF" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.png"
I looked around SO and there has been hints that spaces in my variable can cause an issue, but most of those threads talk about hardcoding the argument names and they only talk about 1 argument. I thought adding double quotes to each variable would solve the issue but it didn't. I also read that using ProcessStartInfo would have helped but again, no dice. I'm going to guess it is the way I formatted the 2 arguments and how I call the command, or I am using ProcessStartInto wrong. Any thoughts?
EDIT: Based on the comments below I did the extra testing testing by waiting for the command window to exit and I found the following error.
Side note: I wouldn't want to use GhostScript just yet because I feel like I am really close to an answer using ImageMagick.
Solution:
string PNGPath = Path.ChangeExtension(Loan_list[f], ".png");
string PDFfile = PNGPath.Replace("png", "pdf");
string PNGfile = PNGPath;
Process process = new Process();
process.StartInfo.FileName = #"C:\Program Files\ImageMagick-6.9.2 Q16\convert.exe";
process.StartInfo.Arguments = "\"" + PDFfile + "\"" +" \"" + PNGPath +"\""; // Note the /c command (*)
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
string err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
It didn't like the way I was formatting the argument string.
This would help you to run you command in c# and also you can get the result of the Console in your C#.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose()l
if(!PDFCheck)
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.EnableRaisingEvents = true;
p.StartInfo.CreateNoWindow = true;
p.startInfo.FileName = "C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe";
p.startInfo.Arguments = arguments;
p.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
//You can receive the output provided by the Command prompt in Process_OutputDataReceived
p.Start();
}
}
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
string s = e.Data.ToString();
s = s.Replace("\0", string.Empty);
//Show s
Console.WriteLine(s);
}
}
I want to compress a folder into a file with the .7z extension, with 7zip.
I would like to know how I would do this, because I'm not sure (which is why I'd asking.)
This is in C#.
Links to pages or sample code would be helpful.
code to zip or unzip file using 7zip
this code is used to zip a folder
public void CreateZipFolder(string sourceName, string targetName)
{
// this code use for zip a folder
sourceName = #"d:\Data Files"; // folder to be zip
targetName = #"d:\Data Files.zip"; // zip name you can change
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"D:\7-Zip\7z.exe";
p.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
this code is used to zip a file
public void CreateZip(string sourceName, string targetName)
{
// file name to be zip , you must provide file name with extension
sourceName = #"d:\ipmsg.log";
// targeted file , you can change file name
targetName = #"d:\ipmsg.zip";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"D:\7-Zip\7z.exe";
p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
this code is used for unzip
public void ExtractFile(string source, string destination)
{
// If the directory doesn't exist, create it.
if (!Directory.Exists(destination))
Directory.CreateDirectory(destination);
string zPath = #"D:\7-Zip\7zG.exe";
try
{
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex) { }
}
I agree that this is a duplicate, but I've used the demo from this codeproject before and it is very helpful:
http://www.codeproject.com/Articles/27148/C-NET-Interface-for-7-Zip-Archive-DLLs
Scroll down the page for the demo and good luck!
Here fileDirPath is the path to my folder which has all my files and preferredPath is the path where I want my .zip file to be.
eg:
var fileDirePath = #“C:\Temp”;
var prefferedPath = #“C:\Output\results.zip”;
private void CreateZipFile(string fileDirPath, string prefferedPath)
{
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"C:\Program Files\7-Zip\7z.exe";
p.Arguments = "a \"" + prefferedPath + "\" \"" + fileDirPath + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
return;
}
I want to generate a couple of hundreds .txt scripts in a C# app, launch GnuPlot and generate .png graphs for each of the scripts I have.
I can launch GnuPlot from C# with the following code:
Process gnuPlotProcess = new Process();
gnuPlotProcess.StartInfo = new ProcessStartInfo(#"C:\Program Files\gnuplot\bin\wgnuplot.exe");
gnuPlotProcess.Start();
The first problem appears when I'm trying to change the current directory, adding this line of code before starting the process:
gnuPlotProcess.StartInfo.Arguments = "cd '" + scriptsPath + "'";
Now GnuPlot doesn't start.
The second problem, which I was able to test working on GnuPlot's default current directory, is when attempting to pass the "load 'script_xxx.txt'" command. Here is the complete code (inspiration from Plotting graph from Gunplot in C#):
Process gnuPlotProcess = new Process();
gnuPlotProcess.StartInfo = new ProcessStartInfo(#"C:\Program Files\gnuplot\bin\wgnuplot.exe");
gnuPlotProcess.StartInfo.RedirectStandardInput = true;
gnuPlotProcess.StartInfo.UseShellExecute = false;
theProcess.Start();
StreamWriter sw = gnuPlotProcess.StandardInput;
sw.WriteLine("load '" + pathToScript + "'");
sw.Flush();
The script that is found on pathToScript should create a .png file, and it works when being launched directly from gnuPlot. But from code, nothing happens.
Any help would be appreciated.
I hope this code will help you:
int N = 1000;
string dataFile = "data.txt"; // one data file
string gnuplotScript = "gnuplotScript.plt"; // gnuplot script
string pngFile = "trajectory.png"; // output png file
// init values
double x = 0, y = 0;
// random values to plot
Random rnd = new Random();
StreamWriter sw = new StreamWriter(dataFile);
// US output standard
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
// generate data for visualisation
for (int i = 0; i < N; i++)
{
x += rnd.NextDouble() - 0.5;
y += rnd.NextDouble() - 0.5;
sw.WriteLine(x.ToString("F3") + "\t" + y.ToString("F3"));
}
sw.Close();
// you can download it from file
string gnuplot_script = "set encoding utf8\n" +
"set title \"Random trajectory\"\n" +
"set xlabel \"Coordinate X\"\n" +
"set ylabel \"Coordinate Y\"\n" +
"set term pngcairo size 1024,768 font \"Arial,14\"\n" +
"set output \"pngFile\"\n" +
"plot 'dataFile' w l notitle\n" +
"end";
// change filenames in script
gnuplot_script = gnuplot_script.Replace("dataFile", dataFile);
gnuplot_script = gnuplot_script.Replace("pngFile", pngFile);
// write sccript to file
sw = new StreamWriter(gnuplotScript, false, new System.Text.UTF8Encoding(false));
sw.WriteLine(gnuplot_script);
sw.Close();
// launch script
ProcessStartInfo PSI = new ProcessStartInfo();
PSI.FileName = gnuplotScript;
string dir = Directory.GetCurrentDirectory();
PSI.WorkingDirectory = dir;
using (Process exeProcess = Process.Start(PSI))
{
exeProcess.WaitForExit();
}
// OPTION: launch deafault program to see file
PSI.FileName = pngFile;
using (Process exeProcess = Process.Start(PSI))
{
}
You can repeat this example with your own data as many times as you want to make many png files
I have a strange requirement. User can upload their video of any format (or a limited format). We have to store them and convert them to .mp4 format so we can play that in our site.
Same requirement also for audio files.
I have googled but I can't get any proper idea. Any help or suggestions....??
Thanks in advance
You can convert almost any video/audio user files to mp4/mp3 with FFMpeg command line utility. From .NET it can be called using wrapper library like Video Converter for .NET (this one is nice because everything is packed into one DLL):
(new NReco.VideoConverter.FFMpegConverter()).ConvertMedia(pathToVideoFile, pathToOutputMp4File, Formats.mp4)
Note that video conversion requires significant CPU resources; it's good idea to run it in background.
Your Answer
please Replace .flv to .mp4 you will get your answer
private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + "OriginalVideo";
//Path of the original file
outputPath = AppPath + "ConvertVideo";
//Path of the converted file
imgpath = AppPath + "Thumbs";
//Path of the preview file
string filepath = Server.MapPath("~/OriginalVideo/" + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(".");
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + "." + ext;
filepath = Server.MapPath("~/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
return false;
}
string outPutFile;
outPutFile = "~/OriginalVideo/" + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
while (a.Exists == false)
{
}
long b = a.Length;
while (i != b)
{
}
string cmd = " -i \"" + inputPath + "\\" + fileName + "\" \"" + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".flv" + "\"";
ConvertNow(cmd);
string imgargs = " -i \"" + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".flv" + "\" -f image2 -ss 1 -vframes 1 -s 280x200 -an \"" + imgpath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".jpg" + "\"";
ConvertNow(imgargs);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + "ffmpeg.exe";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
while (proc.HasExited == false)
{
}
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
ReturnVideo(this.fileuploadImageVideo.FileName.ToString());
}
I know it's a bit old thread but if I get here other people see this too. You shoudn't use it process info to start ffmpeg. It is a lot to do with it. Xabe.FFmpeg you could do this by running just
await Conversion.Convert("inputfile.mkv", "file.mp4").Start()
This is one of easiest usage. This library provide fluent API to FFmpeg.
I am developing a software that will list all the software install
in Computer
now i want to Uninstall it using my Program In C# by
calling the Uninstall Key of that software in
Registry Key
My Program Is
Like That But the Process Is Not Working
var UninstallDir = "MsiExec.exe /I{F98C2FAC-6DFB-43AB-8B99-8F6907589021}";
string _path = "";
string _args = "";
Process _Process = new Process();
if (UninstallDir != null && UninstallDir != "")
{
if (UninstallDir.StartsWith("rundll32.exe"))
{
_args = ConstructPath(UninstallDir);
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\explorer.exe";
_Process.StartInfo.Arguments = Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
_Process.Start();
}
else if (UninstallDir.StartsWith("MsiExec.exe"))
{
_args = ConstructPath(UninstallDir);
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\cmd.exe";
_Process.StartInfo.Arguments = Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
_Process.Start();
}
else
{
//string Path = ConstructPath(UninstallDir);
_path = ConstructPath(UninstallDir);
if (_path.Length > 0)
{
_Process.StartInfo.FileName = _path;
_Process.StartInfo.UseShellExecute = false;
_Process.Start();
}
}
Try this approach:
Process p = new Process();
p.StartInfo.FileName = "msiexec.exe";
p.StartInfo.Arguments = "/x {F98C2FAC-6DFB-43AB-8B99-8F6907589021}/qn";
p.Start();
Refer to this link: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/msiexec.mspx?mfr=true
HTH.
The problem with your misexec.exe code is that running cmd.exe someprogram.exe doesn't start the program because cmd.exe doesn't execute arguments passed to it. But, you can tell it to by using the /C switch as seen here. In your case this should work:
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\cmd.exe";
_Process.StartInfo.Arguments = "/C " + Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
Where all I did was add /C (with a space after) to the beginning of the arguments. I don't know how to get your rundll32.exe code to work, however.
Your solution looks good, but keep a space before \qn:
p.StartInfo.Arguments = "/x {F98C2FAC-6DFB-43AB-8B99-8F6907589021} /qn";
Otherwise it wont work in silent mode.