how to execute a terminal command in c# - c#

I read many post, from them there is this one
c# - Opening the terminal process and pass commands?
I do the exact same thing in my code
Process proc = new System.Diagnostics.Process ();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
where command = export DISPLAY=:0.0
and it goes to my catch, "pplicationName='/bin/bash', CommandLine='-c " cd .. "', CurrentDirectory='', Native error= The system cannot find the file specified."
what do I do differently? even if I try to juste set command = "cd .." it doesn't work

You should probably try setting the full path the executable.
proc.StartInfo.FileName = "C:/SOMEPATH/Bash.exe";
I'm assuming as you are specifying a relative path, it's not resolving it. Possibly because you aren't setting a working directory for the process so it's current dir and the current dir you think it has, are different.

Related

What is the "Error initializing filter 'drawtext' with args..." error in using of ffmpeg at c# process class?

I used this below code for create a resolution of a video and write text on it.
var proc = new System.Diagnostics.Process();
strin OrginalResolution="nhd";
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = ffmpegPath;
proc.StartInfo.Arguments = "-i \"" + fileIn +
"\" -f mp4 -s " + OrginalResolution + " -vf drawtext=fontfile=/OtherProjects/ConvertProj/ff‌​mpeg/OpenSans-Reg‌​ular.ttf:text=Parsa" \"" + fileOut.Split('.')[0] +
".mp4";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
proc.WaitForExit();
string sdsd = proc.StandardError.ReadToEnd();
proc.Close();
I faced with this problem(some string output of StandardError is in below):
Fontconfig error: Cannot load default config file\r\n[Parsed_drawtext_0
#0000000002fd8c20] Cannot find a valid font for the family
Sans\r\n[AVFilterGraph # 0000000000511660] Error initializing
filter'drawtext' with args
'fontfile=/OtherProjects/ConvertProj/ffmpeg/OpenSans-
Regular.ttf:text=parsa'\r\nError opening
filters!\r\n
In cmd the same argument value of process works fine.
I read that this issue related to how to using quotation mark at using
of text property of drawtext in ffmpeg.but I can't find any
solution for solving this issue.
Can anyone help me?
Can anyone help me still?Is this a bug?
I used any solutions for escape from : in my code,but can't solve this problem.
It can't find font.I delete other filters of drawtext to findout that any of filters don't mistake, but still error exists yet.
expansion=none property of drawtext doesn't influence on this case, for escape :.
It works with set working directory address value to proc.StartInfo.WorkingDirectory at process.and full answer is in this link:
https://social.msdn.microsoft.com/Forums/en-US/13dc1101-f1d0-4655-b4af-3f211927d5be/what-is-the-error-initializing-filter-drawtext-with-args-error-in-using-of-ffmpeg-at-c-process?forum=netfxbcl

How can I call the "net share" command from within my program?

I am currently trying to make an application that uses the command net share from the CMD. However, when I press on the button that runs the code, it gives me the following error:
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll.
Here's the code I'm using:
Process cmd = new Process();
cmd.StartInfo.FileName = "net share";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
txt_Logs.Text = cmd.StandardOutput.ReadToEnd();
But when you put ipconfig into the FileName part and /all into the Arguments part, it works perfectly.
The issue is with the StartInfo.File, "net share" is not a valid filename.
Try this
Process cmd = new Process()'
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
If the path contain spaces, you will need to quote it.
Process cmd = new Process();
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share";
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
net is a exe in sys32.. share is an argument.. add it to your aguments..
It is because net share requires Administrative privilege to run this command.
When you try to run only Net Share it will perfectly and it doesn't require any special privilege. But when you try run the command with parameters in the command prompt it will give error stating
System error 5 has occurred.
Access is denied.
So you need to run as administrator
The possible solution might be that you could run the Visual Studio as administrator
To run the command with administrator privilege whereas if the OS is Vista or higher you can do it like below
if (System.Environment.OSVersion.Version.Major >= 6)
{
p.StartInfo.Verb = "runas";
}
As mentioned by #Mohit, this is a problem of admin rights. You can run process as administrator from C# by adding following:
cmd.StartInfo.Verb = "runas";
"net" it's a programm and "share" argument. Try this:
cmd.StartInfo.FileName = "net";
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;

How to rar/unrar with command line parameters

I've looked through the internet on how winrar's command line parameters work, and this is what I have so far
void LOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\WinRAR.exe";
p.StartInfo.Arguments = "rar a -p" + pw + " PL_LOCKED_ARCHIVE.rar " + fld;
p.Start();
}
void UNLOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\WinRAR.exe";
p.StartInfo.Arguments = "unrar x -p" + pw + " PL_LOCKED_ARCHIVE.rar";
p.Start();
}
However it doesn't seem to create any archive anywhere, with a test folder being C:\PicsAndStuff
The StartInfo you define results in running WinRAR.exe with command line:
C:\Program Files\WinRAR\WinRAR.exe unrar x -p pw PL_LOCKED_ARCHIVE.rar
That is of course wrong as you do not want to run WinRAR.exe with first argument being a reference to console version Rar.exe or UnRAR.exe. The result is most likely an error message because of invalid command rar respectively unrar as the first argument must be a or x for WinRAR.exe.
So first of all you need to correct StartInfo:
void LOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\Rar.exe";
p.StartInfo.Arguments = "a -p" + pw + " PL_LOCKED_ARCHIVE.rar " + fld;
p.Start();
}
void UNLOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\UnRAR.exe";
p.StartInfo.Arguments = "x -p" + pw + " PL_LOCKED_ARCHIVE.rar";
p.Start();
}
Further all commands and switches of console version Rar.exe are briefly explained when simply running Rar.exe without any parameter in a command prompt window. Also UnRAR.exe outputs a brief help if executed without any parameter.
Last but not least there is a complete manual for Rar.exe which of course can also extract files and folders from a RAR archive which makes additional usage of UnRAR.exe useless. The manual is text file Rar.txt in program files folder of WinRAR which you should read from top to bottom. I suggest to build the command line while reading it and test the command line first from within a command prompt window.
Note 1:
Rar.exe is shareware. Only UnRAR.exe is freeware.
Note 2:
GUI version WinRAR.exe supports more than console version Rar.exe and therefore the list of switches differ slightly. Complete documentation for WinRAR.exe can be found in help of WinRAR opened with Help - Help Topics or pressing key F1. Open in help on tab Contents the item Command line mode and read. WinRAR.exe is also shareware.
You need to encrypt both file data and headers.
According to Documentation (Command line mode > Switches > "-hp[pwd] - encrypt both file data and headers"):
This switch is similar to -p[p], but switch -p encrypts only file data
and leaves other information like file names visible. This switch
encrypts all sensitive archive areas including file data, file names,
sizes, attributes, comments and other blocks, so it provides a higher
security level.
This is how you can access to it using command line:
Syntax: rar a -hp[MyPassword] -r [filepath] [folderpath]
"C:\Program Files\WinRAR\WinRAR.exe" a -hp12345678 -r d:\zipProject d:\Project
C# Code:
void LOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\WinRAR.exe";
p.StartInfo.Arguments = "rar a -hp" + pw + " PL_LOCKED_ARCHIVE.rar " + fld;
p.Start();
}

Exec batch file not run with space in project folder

I have a simple problem but I don't know how to handle this. That is: I have a simple batch file that remove all file in the folder (for example). I can run it in anywhere but I want to exec it by a application by C#. Everything is allright If the project folder doesn't contains spaces ("Example: C:\Project Test\test.bat" will be error" but "C:\ProjectTest\test.bat" is done").
Below is my source code to run (I say it again: It only error if project folder contain space in folder names). Not error when run file batch if project folder not have space.
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "D:\\prepare.bat";
myProcess.StartInfo.WorkingDirectory = "D:\\";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
//myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
MessageBox.Show(myProcess.StartInfo.Arguments + " " + myString);
myProcess.WaitForExit();
Thanks you.
Try putting script path in quotes:
myProcess.StartInfo.Arguments = "\"D:\\Project Test\\prepare.bat\"";
Enclose your arguments in quotes like this:
myProcess.StartInfo.Arguments = "\"C:\\Project Test\\test.bat\""
or
myProcess.StartInfo.Arguments = #"\"C:\Project Test\test.bat\""
When passed to cmd the arguments must be quoted.
instead of "C:\Project Test\test.bat" use "\"C:\Project Test\test.bat\""

Running cmd commands via .NET?

System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;
And now for some background...
string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
omgwut is something like this:
copy /b a.wav + b.wav + ... + y.wav + z.wav output.wav
And nothing happens at all. So obviously something's wrong. I also tried "copy" as the executable, but that doesn't work.
Try the prefixing your arguments to cmd with /C, effectively saying cmd /C copy /b t.wav ...
According to cmd.exe /? using
/C <command>
Carries out the command specified by
string and then terminates
For your code, it might look something like
// ..
proc0.StartInfo.Arguments = "/C " + omgwut;
Notes:
A good way to test whether your command is going to work is to actually try it from a command prompt. If you try to do cmd.exe copy ... you'll see that the copy doesn't occur.
There are limits to the length of the arguments you can pass as arguments. From MSDN: "The maximum string length is 2,003 characters in .NET Framework applications and 488 characters in .NET Compact Framework applications."
You can bypass the shelling out to command by using the System.IO classes to open the files and manually concatenate them.
Try this it might help you.. Its working with my code.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}
Even you can try this.. this is even better.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments="http://www.microsoft.com";
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited " + proc.StartInfo.Arguments);
Daniels cmd /c idea will work. Keep in mind there is a limit to the length of a command line probably 8k in your case see this for details.
Since you are in a .Net app anyway, File.Copy may be quite a bit easier/cleaner than this approach.

Categories