How would I compress a folder with 7Zip in C#? - c#

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;
}

Related

simple script for generating archives arj

here's code:
string command = string.Empty;
DirectoryInfo dInfoForTesting = new DirectoryInfo(#"E:\TestFiles");
FileInfo[] files = dInfoForTesting.GetFiles();
foreach (FileInfo file in files)
{
string rndPswd = "134";
command = "arj a -m1 -g" + rndPswd + " " + file.Name + ".arj " + file.FullName;
Process.Start(#"C:\ARJ_TEST\programming\test\ARJ.EXE", command);
}
I want to create automatically archives protected by simple password 134 uisng ARJ archiver. But when i run this code for the first file i see the image below. But this file exists!
Please, help to understand me, what i am doing wrong.
EDIT:
i 've decided to rewrite code to run cmd in the folder E:\TestFiles, where there are all files for testing:
ProcessStartInfo startInfo = new ProcessStartInfo
{
WorkingDirectory = #"E:\TestFiles",
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardInput = false
};
foreach (FileInfo file in files)
{
string rndPswd = "134";
command = "arj a -m1 -g" + rndPswd + " " + file.Name + ".arj " + file.Name;
startInfo.Arguments = command;
Process.Start(startInfo);
}
For example, if i run command arj a -m1 -g134 10.arj 10 directly from cmd, arj creates an archive 10.arj. But when i run my code for the first file (10) nothing happens...

Minecraft Launch with C#

i want launch minecraft client with c# but my code doesnt work:
private void Startmc(String a, String b)
{
string javafolder = GetJavaInstallationPath();
string filepath = Path.Combine(javafolder, #"bin\");
Environment.SetEnvironmentVariable("APPDATA", kurulumdosyasi);
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "javaw";
psi.CreateNoWindow = true;
psi.Arguments = "-cp \"" + filepath + ".jar;" + filepath + "lwjgl.jar;" + filepath + "lwjgl_util.jar;" + filepath + "jinput.jar;\" ";
psi.Arguments += "\"-Djava.library.path=" + filepath + "natives\" -Xmx1024M -Xms512M net.minecraft.client.main.Main " + a + " " + b;
p.StartInfo = psi;
p.Start();
}
after click to login button nothing happen
Can't you just open a Process() from the main launcher in the install directory (C:\Program Files (x86)\Minecraft\MinecraftLauncher.exe)? It looks like you're trying to bypass the default behavior...what are you working on?

Getting 7-Zip error - Unable to pass File-names with spaces to Process.Start() method

I need to pass .zip file location into files parameter in the below c# code.
If the file name DOES NOT CONTAIN spaces, everything is working fine. But, if the file name DOES CONTAIN spaces, it is throwing below error.
Cannot find archive
Below is my code: Can anybody please suggest me how can I solve this problem?
static void UnzipToFolder(string zipPath, string extractPath, string[] files)
{
string zipLocation = ConfigurationManager.AppSettings["zipLocation"];
foreach (string file in files)
{
string sourceFileName = string.Empty;
string destinationPath = string.Empty;
var name = Path.GetFileNameWithoutExtension(file);
sourceFileName = Path.Combine(zipPath, file);
destinationPath = Path.Combine(extractPath, name);
var processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = zipLocation;
processStartInfo.Arguments = #"x " + sourceFileName + " -o" + destinationPath;
processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
var process = Process.Start(processStartInfo);
process.WaitForExit();
}
}
Add quotes around the file paths:
processStartInfo.Arguments = "x \"" + sourceFileName + "\" -o \"" + destinationPath + "\"";
Or for readability (with C# 6):
processStartInfo.Arguments = $"x \"{sourceFileName}\" -o \"{destinationPath}\"";
All filenames and paths which contain spaces must be quoted.
Next, regarding your question, how about stating the path like:
7z a -tzip C:\abc\zipfilename C:\"Program files"\DirectoryOrFile

Upload any video and convert to .mp4 online in .net

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.

Unzip a file in c# using 7z.exe

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);

Categories