I'm starting cmd as a process in C# and I want to pass a file path in the argument. How to do it?
Process CommandStart = new Process();
CommandStart.StartInfo.UseShellExecute = true;
CommandStart.StartInfo.RedirectStandardOutput = false;
CommandStart.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
CommandStart.StartInfo.FileName = "cmd";
CommandStart.StartInfo.Arguments = "(here i want to put a file path to a executable) -arg bla -anotherArg blabla < (and here I want to put another file path)";
CommandStart.Start();
CommandStart.WaitForExit();
CommandStart.Close();
EDIT:
Process MySQLDump = new Process();
MySQLDump.StartInfo.UseShellExecute = true;
MySQLDump.StartInfo.RedirectStandardOutput = false;
MySQLDump.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
MySQLDump.StartInfo.FileName = "cmd";
MySQLDump.StartInfo.Arguments = "/c \"\"" + MySQLDumpExecutablePath + "\" -u " + SQLActions.MySQLUser + " -p" + SQLActions.MySQLPassword + " -h " + SQLActions.MySQLServer + " --port=" + SQLActions.MySQLPort + " " + SQLActions.MySQLDatabase + " \" > " + SQLActions.MySQLDatabase + "_date_" + date + ".sql";
MySQLDump.Start();
MySQLDump.WaitForExit();
MySQLDump.Close();
You need to put the file path in double quotes and use a verbatim string literal (#) as SLaks mentioned.
CommandStart.StartInfo.Arguments = #"""C:\MyPath\file.exe"" -arg bla -anotherArg";
Example with an OpenFileDialog
using(OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filePath = "\"" + ofd.FileName + "\"";
//..set up process..
CommandStart.StartInfo.Arguments = filePath + " -arg bla -anotherArg";
}
}
Update to comment
You can format your string using String.Format.
string finalPath = String.Format("\"{0}{1}_date_{2}.sql\"", AppDomain.CurrentDomain.BaseDirectory, SQLActions.MySQLDatabase, date);
Then pass finalPath into the arguments.
Related
The conversion is successfully worked but during conversion command prompt is open for a fraction of second..I dont want to show it
The code is:
string[] name = new string[all_audio_name.Count()];
string mpfile;
System.Diagnostics.Process pro = null;
mpfile = Path.GetFileName(all_audio_name[j]).Replace(".wav", ".mp3");
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
string outfile = "-b 32 --resample 22.05 -m j " + "\"" + new_path + "\\" + Path.GetFileName(all_audio_name[j]) + "\"" + " " + "\"" + new_path + "\\" + Path.GetFileNameWithoutExtension(all_audio_name[j]) + ".mp3" + "\"";
psi.FileName = HttpContext.Current.Server.MapPath("~/Dependencies/lame.exe");
psi.Arguments = outfile;
psi.UseShellExecute = false;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
pro = System.Diagnostics.Process.Start(psi); //IGNORE VARIABLE NAME
after System.Diagnostics.Process.Start(psi); line cmd prompt appear..plz suggest me to hide it..
I want to automate using gsutil in c #.
I use the "gsutil cp" command . If the file is small , the copied successfully . However, the file size is more than 10MB, the command is not end . I 've waited a long time , the command does not end .
This is my code.
String currentUser = Environment.UserName;
if (File.Exists(#"C:\Users\" + currentUser + #"\" + botoFileName) == false)
{
log.Error("can't find the confileFileName (" + botoFileName + ")");
return false;
}
log.Info("==========================================================");
log.Info("fileKey = " + fileKey);
string resultPro = null;
string resultError = null;
System.Diagnostics.ProcessStartInfo proInfo = new System.Diagnostics.ProcessStartInfo();
System.Diagnostics.Process pro = new System.Diagnostics.Process();
proInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
proInfo.CreateNoWindow = true;
proInfo.UseShellExecute = false;
proInfo.RedirectStandardOutput = true;
proInfo.RedirectStandardInput = true;
proInfo.RedirectStandardError = true;
pro.StartInfo = proInfo;
pro.Start();
pro.StandardInput.Write("c:" + Environment.NewLine);
pro.StandardInput.Write(#"set BOTO_PATH=C:\Users\" + currentUser + #"\" + botoFileName + Environment.NewLine);
if (usingCloudSdk.Equals("true"))
{
//when using google sdk and python
pro.StandardInput.Write(#"gsutil cp " + fileKey + " " + gcsPath + Environment.NewLine);
}
else
{
//when using only gsutil and python
pro.StandardInput.Write(#"cd C:\gsutil\gsutil" + Environment.NewLine);
pro.StandardInput.Write(#"python gsutil -m cp " + fileKey + " " + gcsPath + Environment.NewLine);
}
pro.StandardInput.Close();
resultPro = pro.StandardOutput.ReadToEnd();
resultError = pro.StandardError.ReadToEnd();
pro.WaitForExit();
pro.Close();
log.Info(resultPro);
log.Info(resultError);
log.Info("==========================================================");
if (resultError.IndexOf("Exception") != -1 || resultError.IndexOf("Fail") != -1)
{
return false;
}
return true;
please help me.
I need to get the following thing into the CMD in C#:
navigate to location
start ftp.exe
open server
user
password
get file
close
quit
How do I accomplish that?
Please mind that I can not use Net.FtpWebRequest for this particular task.
Is there a way to log in in one line like ftp user:password#host?
Try calling a bat file?
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = #"/c e:\test\ftp.bat";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
Call ftp.bat file
Ftp.Bat file contains...
ftp -s:commands.ftp
Then in your commands.ftp
open <server_address>
<userid>
<password>
recv <source_file> <dest_file>
bye
Or something similar.
The solution I went with:
C#:
String ftpCmnds = "open " + folder.server + "\r\n" + folder.cred.user + "\r\n" + folder.cred.password + "\r\nget " + file + "\r\nclose\r\nquit";
//This is a custom method that I wrote:
Output.writeFile(basePath + "\\" + Util.getDateFormated(reverseDate) + "\\" + parentFolder + "\\" + folder.server + "\\", "tmp.txt", ftpCmnds);
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.WindowStyle = ProcessWindowStyle.Hidden;
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
Console.WriteLine("Forcing Download from " + folder.server + folder.path + " of " + file + "\n"); log += "\r\n\r\n\t\t- Forcing Download from " + folder.server + folder.path + file + "\tto\t" + basePath + "\\" + Util.getDateFormated(reverseDate) + "\\" + parentFolder + "\\" + folder.server + "\\" + file;
sw.WriteLine("cd " + basePath + "\\" + Util.getDateFormated(reverseDate) + "\\" + parentFolder + "\\" + folder.server + "\\");
sw.WriteLine("ftp -s:tmp.txt");
sw.WriteLine("del tmp.txt");
p.Close();
}
}
The only "bad" thing is that the tmp.txt file, which is availiable for the time it requires to download the file, contains the username and password of the server as plain text. :-/
I could append a random String to the name though to make it a little more secure.
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 building a gui for a commandline program.
In txtBoxUrls[TextBox] file paths are entered line by line.
If the file path contains spaces the program is not working properly.
The program is given below.
string[] urls = txtBoxUrls.Text.ToString().Split(new char[] { '\n', '\r' });
string s1;
string text;
foreach (string s in urls)
{
if (s.Contains(" "))
{
s1 = #"""" + s + #"""";
text += s1 + " ";
}
else
{
text += s + " ";
}
}
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = #"wk.exe";
proc.StartInfo.Arguments = text + " " + txtFileName.Text;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
//Get program output
string strOutput = proc.StandardOutput.ReadToEnd();
//Wait for process to finish
proc.WaitForExit();
For example if the file path entered in txtBoxUrls is "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm", The program will not work. This file path with double quotes will work in the windows command line(I am not using the GUI) nicely.
What would be the solution.
proc.StartInfo.Arguments = text + " " + txtBoxUrls.Text + " " + txtFileName.Text;
In this line, text already contains the properly quoted version of your txtBoxUrls strings. Why do you add them again in unquoted form (+ txtBoxUrls.Text)? If I understood your code corrently, the following should work:
proc.StartInfo.Arguments = text + " " + txtFileName.Text;
In fact, since txtFileName.Text could probably contain spaces, you should quote it as well, just to be sure:
proc.StartInfo.Arguments = text + " \"" + txtFileName.Text + "\"";
(or, using your syntax:)
proc.StartInfo.Arguments = text + #" """ + txtFileName.Text + #"""";
Usually to get around spaces in filenames, you'll need to wrap your argument in double quotes. If you leave out the quotes the program will think it has two arguments. Something like this...
wk.exe "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm"
Also, this line appears to have too many quotes. Four, instead of three:
s1 = #"""" + s + #"""";
Take a look at the Path class - http://msdn.microsoft.com/en-us/library/system.io.path.aspx
Path.combine might be what you are looking for.