I'm having an issue where my cmd windows is just blank when executed from code. I've searched here and there for some solutions. And tried a few different things myself.
Running it with a normal .bat file works just fine.. But just not from my C# application.
Note: the ffmpeg is being run perfectly, but just not showing anything in the cmd window when executed from code.
image at the bottom.
I'll update this if I find a solution.. Unless you guys do it first ;)
Code:
private async void RunFfmpeg()
{
await Task.Run(() =>
{
String destFolder = null;
String sourceFolder = null;
int listCount = 0;
this.Dispatcher.Invoke(() =>
{
destFolder = textDest.Text;
sourceFolder = textSource.Text;
listCount = listFiles.Items.Count;
});
foreach (FileInfo fileC in listFiles.Items)
{
//Changing old extension to mp4
string oldFileName = fileC.ToString();
string newFileName = null;
string[] extension = oldFileName.Split('.');
newFileName = extension[0] + ".mp4";
string newDir = destFolder + "\\" + extension[0];
DirectoryInfo createDir = new DirectoryInfo(newDir);
if (!createDir.Exists)
{
createDir.Create();
}
//Gathering folders and all I need...
string output = "\"" + destFolder + "\\" + extension[0] + "\\" + newFileName + "\"";
string input = "\"" + sourceFolder + "\\" + oldFileName + "\"";
var startInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "cmd.exe",
//Arguments = $"-i {input} {output}",
Arguments = $"/c ffmpeg -i {input}" + " -c:a copy -c:v copy " + $"{output}",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
WorkingDirectory = Directory.GetCurrentDirectory()
};
Process p = new Process();
p.StartInfo = startInfo;
p.OutputDataReceived += P_OutputDataReceived;
p.Start();
p.WaitForExit();
}
});
}
Here is where I read the output:
private void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.Dispatcher.Invoke(() =>
{
//string cmdBox = cmdOutput.Text;
//cmdOutput.AppendText(cmdBox);
//cmdOutput.Clear();
cmdOutput.AppendText(e.Data);
});
}
Related
I'm using windows 10.
I'm trying to compile a c++ file within c# using MinGW(the MinGW folder is in the projects directory), but it won't compile a resource script (using windres).
Whenever I use windres in cmd it says: "C:/Users/username/AppData/Local/Temp/my.rc:1: unrecognized escape sequence".
but still works.
But when I run the exact same command through c# (by creating a process) it doesn't work at all and says: "The filename, directory name, or volume label syntax is incorrect.".
My code:
String tempDir = Path.GetTempPath();
String file = tempDir + "my.rc";
using (StreamWriter writer = new StreamWriter(file, false, Encoding.ASCII))
{
if (!textIcon.Text.Equals(""))
await writer.WriteLineAsync("25 ICON \"" + textIcon.Text + "\"");
if (checkAdmin.Checked)
{
String manifest = tempDir + #"\manifest.xml";
createManifest(manifest);
await writer.WriteLineAsync("55 24 \"" + manifest + "\"");
}
}
String args2 = "/c \"" + Path.Combine(gccLocation, "windres.exe") + "\" -o \"" + Path.Combine(tempDir, "my.o").Replace("\\", "/") + "\" \"" + file.Replace("\\", "/") + "\"";
//Debug
//args2 = "/k echo " + args2;
ProcessStartInfo psi2 = new ProcessStartInfo();
psi2.FileName = "CMD.exe";
psi2.Arguments = args2;
psi2.UseShellExecute = false;
psi2.CreateNoWindow = true;
//Debug
//psi2.CreateNoWindow = false;
Process windres = Process.Start(psi2);
windres.WaitForExit();
if(windres.ExitCode != 0)
{
MessageBox.Show("Error: Could not create resource file (" + windres.ExitCode + ")");
}
Ended up using a batch file to run the command.
String args2 = "windres.exe -i \"" + Path.GetFullPath(file) + "\" -o \"" + Path.Combine(tempDir, "my.o") + "\"" ;
using (StreamWriter writer = new StreamWriter(tempDir + #"\my.bat", false, Encoding.ASCII))
{
await writer.WriteLineAsync("#echo off");
await writer.WriteLineAsync("cd " + Path.GetFullPath(gccLocation));
await writer.WriteLineAsync(args2);
}
//Debug
//args2 = "/k echo " + args2;
ProcessStartInfo psi2 = new ProcessStartInfo();
psi2.FileName = tempDir + #"\my.bat";
psi2.UseShellExecute = false;
psi2.CreateNoWindow = true;
//Debug
//psi2.CreateNoWindow = false;
Process windres = Process.Start(psi2);
windres.WaitForExit();
I need to write a small utility to rebuild solution. I am using below code to do the same.
string solutionFile = #"E:\Projects\TFS\Code\WebSite.sln";
string cmd1 = #"""C:\Program Files\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" x86" + " &devenv " + "\"" + solutionFile + "\"" + " /rebuild release";
cmd1 = "\"" + cmd1 + "\"";
String command = String.Format("{0} {1}", #"/k ", cmd1);
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true
};
cmdsi.Arguments = command;
using (Process cmd = Process.Start(cmdsi))
{
using (StreamReader reader = cmd.StandardOutput)
{
string result = reader.ReadToEnd();
listBox1.Items.Add(result);
}
}
If you will observe in command prompt then you can see executions output but same thing is not getting reflected in list box.
Please help to solve this issue.
Thank you in advance.
You can redirect the output to a temporary file and then can read the file like-
string cmd1 = "help > e:/temp.txt"; //e:/temp.txt is temporary file where the output is redirected.
String command = String.Format("{0} {1}", #"/k ", cmd1);
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe")
{
//You don't need to read console outputstream
//UseShellExecute = false,
//RedirectStandardOutput = true
};
cmdsi.Arguments = command;
using (Process cmd = Process.Start(cmdsi))
{
//Check if file exist or you can wait till the solution builds completely. you can apply your logic to wait here.
if (File.Exists("E:/temp.txt"))
{
//Read the files here
string[] lines = File.ReadAllLines("E:/temp.txt");
//Do your work here
}
}
You can do it async:
string solutionFile = #"E:\Projects\TFS\Code\WebSite.sln";
string batFile = #"C:\Program Files\Microsoft Visual Studio 11.0\VC\vcvarsall.bat";
string args = "x86" + " &devenv " + "\"" + solutionFile + "\"" + " /rebuild release";
ProcessStartInfo cmdsi = new ProcessStartInfo(batFile)
{
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true
};
using (Process cmd = new Process())
{
cmd.StartInfo = cmdsi;
cmd.OutputDataReceived += (sender, args) => listBox1.Items.Add(string.IsNullOrEmpty(args.Data) ? string.Empty : args.Data);
cmd.Start();
}
Is there any way to install JMF in silent mode using C#?
I have jmf.iss and JMF setup.exe and I'm having problems setting the silent parameter:
string[] programArray = {"SETUP.exe","Java-jre-7u45-windows-i586"};
foreach (string path in programArray)
{
using (Process p = new Process())
{
string arg = "passive";
if (path.Contains("SETUP"))
{
arg = "s /f1" + AppDomain.CurrentDomain.BaseDirectory + #"jmf.iss";
}
else if (path.Contains("Java"))
{
arg = "s";
}
p.StartInfo = new ProcessStartInfo(Application.StartupPath + "\\" + path);
p.StartInfo.Arguments = string.Format("/" + arg, path);
p.Start();
//p.WaitForExit();
while (!p.HasExited)
{
Application.DoEvents();
}
}
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.
when I run this code:
static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var searchDirectory = new DirectoryInfo(currentDirectory);
var queryMatchingFiles =
from file in searchDirectory.GetFiles()
let fileContent = System.IO.File.ReadAllText(file.Name)
select file.Name;
StreamWriter outputCacheMeta = new StreamWriter(#"output.txt");
foreach (var fileName in queryMatchingFiles.Where(fileName => !fileName.EndsWith(".txt") && !fileName.EndsWith(".exe") && !fileName.EndsWith(".xz")))
{
// start the converion utility
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "xz.exe";
startInfo.Arguments = "-k -z " + fileName;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
using (Process p = Process.Start(startInfo))
{
while (!p.HasExited)
{
Thread.Sleep(300);
}
}
//Process.Start(startInfo);
Console.WriteLine(string.Format("Compressing file: '{0}'", fileName.ToString()));
// generate final string
FileInfo inFile = new FileInfo(fileName);
FileInfo outFile = new FileInfo(fileName + ".xz");
outputCacheMeta.WriteLine("<ContentFile Name=\"" + fileName.ToString() + "\" Size=\"" + inFile.Length.ToString() + "\" SHA1Hash=\"" + HashCalc.GetSHA1Hash(fileName).ToString() + "\" CompressedSize=\"" + outFile.Length.ToString() + "\" />");
//Console.WriteLine(string.Format(("<ContentFile Name=\"" + fileName.ToString() + "\" Size=\"" + inFile.Length.ToString() + "\" SHA1Hash=\"" + HashCalc.GetSHA1Hash(fileName).ToString() + "\" CompressedSize=\"" + outFile.Length.ToString() + "\" />")));
}
}
it does not print everything in the output file (output.txt), it prints this: http://pastebin.com/1vTQZVih (sorry for external link).
The problem is that it suddenly 'stops' writing to the output file.
Thanks!
You are not Flush()ing or Close()ing your StreamWriter before your program exits. Some of your file data is buffered to be written to the file, but will not actually get written until your flush and and close the stream.