C# + 7z.exe doesn't seem to work [duplicate] - c#

This question already has answers here:
Unzip a file in c# using 7z.exe
(6 answers)
Closed 8 years ago.
string path = #"C:\Users\<user>\Documents\Visual Studio\Projects\7ZipFile\RequiredDocs\";
ProcessStartInfo zipper = new ProcessStartInfo(#"C:\Program Files\7-Zip\7z.exe");
zipper.Arguments = string.Format("a -t7z {0}.7z {0} *.txt -mx9", path);
zipper.RedirectStandardInput = true;
zipper.UseShellExecute = false;
zipper.CreateNoWindow = true;
zipper.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(zipper);
Goal: Zip all *.txt file(s) within "path" and save that zipped file within "path" and these .txt files should not be present in the "path" after zipping
When I run the code, nothing seems to happen (0 error)...
Please help!
Thank you
UPDATE: I am using 7Zip and have installed 7Zip application on Windows where this code will be used w/ .NET 3.5.

The normal way of using 7Zip from a program is to invoke 7za.exe (not the installed 7z program) and include 7za with your application.
This page has a good tutorial on how to use it. Works great every time I have needed to zip/7zip programmatically.
You could also use the ZipArchive class if you want normal zip functionality in a pure .NET way (requires .NET 4.5)
Also, your path should be in quotes in case there is a space. Note that the quotes are escaped with '\'. "" is also a valid escape sequence for a quote in C#:
string.Format("a -t7z \"{0}.7z\" \"{0}\" *.txt -mx9", path);

Here's an example from my application. This example extracts an archive but it shows you how to set up the process. Just change the command to 7z and the arguments. This example assumes you're shipping 7za.exe with your application. Good luck.
public static bool ExtractArchive(string f) {
string tempDir = Environment.ExpandEnvironmentVariables(Configuration.ConfigParam("TEMP_DIR"));
if (zipToolPath == null) return false;
// Let them know what we're doing.
Console.WriteLine("Unpacking '" + System.IO.Path.GetFileName(f) + "' to temp directory.");
LogFile.LogDebug("Unpacking '" + System.IO.Path.GetFileName(f) + "' to temp directory '" + tempDir + "'.",
System.IO.Path.GetFileName(f));
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
if (pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE) {
p.StartInfo.FileName = "\"" + Path.Combine(zipToolPath, zipToolName) + "\"";
p.StartInfo.Arguments = " e " + "-y -o" + tempDir + " \"" + f + "\"";
} else {
p.StartInfo.FileName = Path.Combine(zipToolPath, zipToolName);
p.StartInfo.Arguments = " e " + "-y -o" + tempDir + " " + f;
}
try {
p.Start();
} catch (Exception e) {
Console.WriteLine("Failed to extract the archive '" + f + "'.");
LogFile.LogError("Exception occurred while attempting to list files in the archive.");
LogFile.LogExceptionAndExit(e);
}
string o = p.StandardOutput.ReadToEnd();
p.WaitForExit();
string[] ls = o.Split('\n');
for (int i = 0; i < ls.Count(); i++) {
string l = ls[i].TrimEnd('\r');
if (l.StartsWith("Error")) {
LogFile.LogError("7za: Error '" + ls[i + 1] + "'.", f);
Console.WriteLine("Failed to extract the archive '" + f + "'.");
return false;
}
}
return true;
}

Related

Executing line commands arguments with 2 variables problem c#

I am trying to open my .exe "application" with 2 arguments. When I write the command line myself without " " it don't want to work. When I write the command line using "C:/Path" "A" "B" it does work.
How do I fix this?
if(element.SaveType == "1")
{
DirectoryInfo srcDir = new DirectoryInfo((string)element.SourcePath);
DirectoryInfo dstDir = new DirectoryInfo((string)element.DestinationPath);
if (element.didEncrypt == true)
{
if (Directory.GetFiles(srcDir.FullName, ((string)element.EncryptExt)).Length == 0)
{
string pat = System.IO.Path.Combine(#"C:\Users\Client Fractal\source\repos\CryptoSoft\CryptoSoft\bin\Debug\netcoreapp3.0\CryptoSoft.exe");
Process p = new Process();
p.StartInfo.FileName = pat;
p.StartInfo.Arguments = srcDir.FullName + dstDir.FullName; // source / target;
Console.WriteLine(p.StartInfo.Arguments);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
}
}
}
Command-line arguments are space-character delimited, so you'd need to insert a space character or your arguments will end up getting squashed together.
p.StartInfo.Arguments = srcDir.FullName + " " + dstDir.FullName;
But of course, if either srcDir.FullName or dstDir.FullName contain space characters of their own (and FullName suggests they do), you will need to surround them with double quote characters.
p.StartInfo.Arguments = "\"" srcDir.FullName + "\" \"" + dstDir.FullName + "\"";

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.

Merge videos in c# asp.net using ffmpeg

Is it possible to merge the two videos by c# asp.net with the help of ffmpeg. In the ffmpeg documentation they gave us cat command. But it wont works in asp.net. I thought it only for linux.
cat intermediate1.mpg intermediate2.mpg > intermediate_all.mpg
asp.net execute this command but there is no output. Help me.
namespace demo
{
public partial class Default : System.Web.UI.Page
{
protected void Button2_Click(object sender, EventArgs e)
{
string strFile = "cars1.flv";
MergeFiles(strFile);
}
public void MergeFiles(string strFile)
{
string strParam;
string Path_FFMPEG = Server.MapPath("~/ffmpeg/bin/ffmpeg.exe");
//Converting a video into mp4 format
string strOrginal = Server.MapPath("~/Videos/");
strOrginal = strOrginal + strFile;
string strConvert = Server.MapPath("~/Videos/ConvertedFiles/");
string strExtn = Path.GetExtension(strOrginal);
if (strExtn != ".mp4")
{
strConvert = strConvert + strFile.Replace(strExtn, ".mp4");
strParam = "-i " + strOrginal + " " + strConvert;
//strParam = "-i " + strOrginal + " -same_quant " + strConvert;
process(Path_FFMPEG, strParam);
}
//Merging two videos
String video1 = Server.MapPath("~/Videos/Cars1.mp4");
String video2 = Server.MapPath("~/Videos/ConvertedFiles/Cars2.mp4");
String strResult = Server.MapPath("~/Videos/ConvertedFiles/Merge.mp4");
//strParam = "-loop_input -shortest -y -i " + video1 + " -i " + video2 + " -acodec copy -vcodec mjpeg " + strResult;
strParam = " -i " + video1 + " -i " + video2 + " -acodec copy -vcodec mjpeg " + strResult;
process(Path_FFMPEG, strParam);
}
public void process(string Path_FFMPEG, string strParam)
{
try
{
Process ffmpeg = new Process();
ProcessStartInfo ffmpeg_StartInfo = new ProcessStartInfo(Path_FFMPEG, strParam);
ffmpeg_StartInfo.UseShellExecute = false;
ffmpeg_StartInfo.RedirectStandardError = true;
ffmpeg_StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo = ffmpeg_StartInfo;
ffmpeg_StartInfo.CreateNoWindow = true;
ffmpeg.EnableRaisingEvents = true;
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
ffmpeg.Dispose();
ffmpeg = null;
}
catch (Exception ex)
{
}
}
}
}
Finally i found the answer for my own question.
The following method resolves my problem.
public void MergeFiles(string strFile)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = Server.MapPath("~/app.bat");
p.Start();
p.WaitForExit();
p.Dispose();
}
app.bat
The app.bat contains the following code.
copy e:\cars1.mpg /b + e:\cars2.mpg /b e:\output.mpg /b
NOTE: This is for windows only. That's why "cat" command doesn't works. Instead of "cat" command we use copy command.
Creating app. Bat file double the file size but it play as single. Still problem not resolved. You should try ffmpeg concat command approach in which you need to create a text file that contain files names and this file should be on same folder where mp4 file are. the below code will help you i was facing the same issue. My task was to merge two mp4 files and I merge successfully when I was doing it from Command prompt. But stuck when I was doiing it through asp. Net. My issue resolved by given correct path and remove ffmpeg from command. For E. G( ffmepg - f concat TO - f concat)
Dim _ffmpeg As String = "D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\bin\ffmpeg.exe"
Dim params = "-f concat -i D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\mylist2.txt -c copy D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\0104.mp4"
Dim _FFmpegProcessPropertys As New ProcessStartInfo
_FFmpegProcessPropertys.FileName = _ffmpeg
_FFmpegProcessPropertys.Arguments = params
_FFmpegProcessPropertys.UseShellExecute = False
_FFmpegProcessPropertys.RedirectStandardOutput = True
_FFmpegProcessPropertys.RedirectStandardError = True
_FFmpegProcessPropertys.CreateNoWindow = True
Dim FFmpegProcess = Process.Start(_FFmpegProcessPropertys)

How to uninstall Software using c# by calling Software UninstallString Listed in Registry file of that Software But the Process Is Not Working

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.

How to capture thumbnail for video while uploading it in ASP.NET?

I want to know how to capture thumbnail for video while uploading it in ASP.NET ?
Well first of all, you will also need to convert it to MP4 which will work on everywhere. For that you can use ffmpeg tool,
To Create Thumbnail,
//Create Thumbs
string thumbpath, thumbname;
string thumbargs;
string thumbre;
thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Video\\Thumb\\";
thumbname = thumbpath + withoutext + "%d" + ".jpg";
thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:07 -s 150x150 " + thumbname;
Process thumbproc = new Process();
thumbproc = new Process();
thumbproc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
thumbproc.StartInfo.Arguments = thumbargs;
thumbproc.StartInfo.UseShellExecute = false;
thumbproc.StartInfo.CreateNoWindow = false;
thumbproc.StartInfo.RedirectStandardOutput = false;
try
{
thumbproc.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
thumbproc.WaitForExit();
thumbproc.Close();
However, for more details about the code, see this link.
http://ramcrishna.blogspot.com/2008/09/playing-videos-like-youtube-and.html
And you will need to change paths according to your web application's path.

Categories