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.
Related
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);
});
}
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 have Multiple folder path:
SourceFilePath="C:\Users\Anuj\Desktop\PSI"
SourceFilePath1="C:\Users\Anuj\Desktop\Google"
SourceFilePath2="C:\Users\Anuj\Desktop\Isp"
I want to Compress These path Using 7zip Command line code along with a Zip Password.
Edit:
//Declare and instantiate a new process component.
System.Diagnostics.Process proc;
proc = new System.Diagnostics.Process();
//Do not receive an event when the process exits.
proc.EnableRaisingEvents = false;
//The "/C" Tells Windows to Run The Command then Terminate
string strCmdLine;
strCmdLine = "/C cd c:\\Program Files\\7-Zip\\ ";
strCmdLine += " & 7z a "// here i need help
System.Diagnostics.Process.Start("CMD.exe", strCmdLine);
proc.Close();
What I actually Did:
var MultiplePathFolders=SourceFilePath+SourceFilePath1+SourceFilePath2
System.Diagnostics.Process proc;
proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
string strCmdLine;
strCmdLine = "/C cd c:\\Program Files\\7-Zip\\ ";
strCmdLine += " & 7z a " + SyncPath + "\\" + ZipName + "-FileName.7z " + MultiplePathFolders + " -p" + DecryptedPassword + "";
System.Diagnostics.Process.Start("CMD.exe", strCmdLine);
proc.Close();
You can do like this:
string yourPassWord = "Hello";
string yourZipPath="D:\\my7z.7z"; // Your 7z file path
//string yourZipPath="D:\\myZip.zip"; // Or your zip file path
System.Diagnostics.Process proc;
proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
List<string> foldersAndFiles = new List<string>();
foldersAndFiles.Add("D:\\F1"); // Add folder
foldersAndFiles.Add("D:\\F2"); // Add folder
foldersAndFiles.Add("D:\\file.txt"); // Add file
string cmd = "a -tzip -p\"" + yourPassWord + "\" \"" + your7zPath + "\"";
foreach(var item in foldersAndFiles)
{
cmd += " \"" + item + "\"";
}
proc.StartInfo.FileName
= "c:\\Program Files\\7-Zip\\7z.exe"; // Be sure this file exist.
proc.StartInfo.Arguments = cmd;
proc.Start();
proc.Close();
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'm using Asp.Net C# Framework 4 and currently developing a video conversion application. I'm also using ffmpeg to convert from all uploaded formats to flv. I'm first converting uploaded file to mpg and after to flv due to problems I encountered while trying conversion directly to flv from mp4 sometimes. But ffmpeg freezes as soon as it's done with conversion process to mpg file. When I run task manager and check the processes list, it just stands there using no CPU resource. When I end the ffmpeg process directly from task manager, other process take place which converts from mpg to flv and preview file (jpg) and works smoothly. Due to freezing of first process, the second process cannot start when I try to upload from my web page's file upload form. I appreciate any response from now. Here is my code:
string duration = "00:00:00";
//converting video
Process ffmpeg;
ffmpeg = new Process();
// convert to mpg 1st
ffmpeg.StartInfo.Arguments = " -i \"" + Server.MapPath("static/user/vid/") + videolink + "\" -f mpeg -b 300k -ac 2 -ab 128k -ar 44K \"" + Server.MapPath("static/user/vid/") + mpglink + "\"";
ffmpeg.StartInfo.FileName = Page.MapPath("bin/ffmpeg.exe");
ffmpeg.StartInfo.CreateNoWindow = true;
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
// mpg 2 flv
ffmpeg = new Process();
ffmpeg.StartInfo.Arguments = " -i \"" + Server.MapPath("static/user/vid/") + mpglink + "\" -f flv -s 624x352 \"" + Server.MapPath("static/user/vid/") + flvlink + "\"";
ffmpeg.StartInfo.FileName = Page.MapPath("bin/ffmpeg.exe");
ffmpeg.StartInfo.CreateNoWindow = true;
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.Start();
ffmpeg.BeginOutputReadLine();
string error = ffmpeg.StandardError.ReadToEnd();
ffmpeg.WaitForExit();
try
{
duration = error.Substring(error.IndexOf("Duration: ") + 10, 8);
}
catch
{
}
if (ffmpeg.ExitCode != 0)
{
ltrUpload.Text = "<div class=\"resultbox-negative\" id=\"divResult\">Problem occured during upload process. Error code: " + error + "<br>" + "</div>";
return;
}
ffmpeg.Close();
// generate preview image
ffmpeg.StartInfo.Arguments = " -i \"" + Server.MapPath("static/user/vid/") + flvlink + "\" -s 624x352 -ss 00:00:03 -an -vframes 1 -f image2 -vcodec mjpeg \"" + Server.MapPath("static/user/vid/") + flvlink.Replace(".flv", ".jpg") + "\"";
ffmpeg.StartInfo.FileName = Page.MapPath("bin/ffmpeg.exe");
ffmpeg.StartInfo.CreateNoWindow = true;
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
// deleting original file and mpg
FileInfo fi = new FileInfo(Server.MapPath("static/user/vid/") + videolink);
if (fi.Exists) fi.Delete();
fi = new FileInfo(Server.MapPath("static/user/vid/") + mpglink);
if (fi.Exists) fi.Delete();
I know this is a very old question, but if someone gets here because of a Google search, the answer is the following:
You would have to read the redirected error output of the first ffmpeg process, too, even if you do not need it. It will result in a deadlock if you do not read the redirected error output because your program will wait for the process to finish, but the process waits for the filled error output stream to be read. You can look it up here.
// convert to mpg 1st
ffmpeg.StartInfo.Arguments = " -i \"" + Server.MapPath("static/user/vid/") + videolink + "\" -f mpeg -b 300k -ac 2 -ab 128k -ar 44K \"" + Server.MapPath("static/user/vid/") + mpglink + "\"";
ffmpeg.StartInfo.FileName = Page.MapPath("bin/ffmpeg.exe");
ffmpeg.StartInfo.CreateNoWindow = true;
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.Start();
// Use asynchronous read operations on at least one of the streams.
// Reading both streams synchronously would generate another deadlock.
ffmpeg.BeginOutputReadLine();
string tmpErrorOut = ffmpeg.StandardError.ReadToEnd();
ffmpeg.WaitForExit();
ffmpeg.Close();
So you would have to read the redirected error and output streams like you did with your second ffmpeg process.
The same goes for your generating image preview part!
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 + "Upload\\Videos\\OriginalVideo";
//Path of the original file
outputPath = AppPath + "Upload\\Videos\\ConvertVideo";
//Path of the converted file
imgpath = AppPath + "Upload\\Videos\\Thumbs";
//Path of the preview file
string filepath = Server.MapPath("../Upload/Videos/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("../Upload/Videos/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
return false;
}
string outPutFile;
outPutFile = "../Upload/Videos/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);
ViewState["fileName"] = fileName.Remove(fileName.IndexOf(".")) + ".wmv";
string imgargs = " -i \"" + inputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".wmv" + "\" -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 "wmvtool2.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)
{ }
}
if (fileuploadImageVideo.HasFile)
{
ReturnVideo(this.fileuploadImageVideo.FileName.ToString());
string filename = fileuploadImageVideo.PostedFile.FileName;
fileuploadImageVideo.SaveAs(Server.MapPath("../upload/Video/"+filename));
objfun.Video = filename ;
}