enter image description here
I setting my WorkerService appsettings.json like below
"AppRun": {
"App1": {
"AppName": "CheckDataForm",
"AppPath": "D:\\2021-Project\\Project\\CheckDataForm-MSSQL\\CheckDataForm\\bin\\Debug\\net5.0-windows\\CheckDataForm.exe"
},
"App2": {
"AppName": "notepad++",
"AppPath": "C:\\Program Files\\Notepad++\\notepad++.exe"
},
and call the app like this:
//i is foreach count
var AppName = _config["AppRun:App"+i+":AppName"];
var AppPath = _config["AppRun:App" + i + ":AppPath"];
//check file exist
var fileExist = System.IO.File.Exists(AppPath);
if ( !String.IsNullOrEmpty (AppName) && !String.IsNullOrEmpty(AppPath) &&
fileExist )
{
//find APP
var processApp = Process.GetProcessesByName(AppName);
//can't find app
if (processApp.Length <=0 )
{
try
{
Process proc = new Process();
proc.StartInfo.FileName = AppPath;
proc.StartInfo.WorkingDirectory =
System.IO.Path.GetDirectoryName(AppPath);
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.WindowStyle =
ProcessWindowStyle.Maximized;
proc.Start();
}
catch (Exception ex)
{
var error = ex;
}
}
}
the Process can Start notepad++ And CheckDataForm , but notepad++ And CheckDataForm AP run in [Background processes] , I need AP Run in [Apps]
How To Executable under Apps , Not in Background Process
, like image show
You can execute the program using the CMD:
Process proc = new Process();
proc.StartInfo.FileName = "CMD";
proc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(AppPath);
proc.StartInfo.Arguments = "/C "+AppPath;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
proc.Start();
That way will be ran as if you run it as the logged user.
Since you are using a Service, you could use a predefined TASK from the Task Scheduler to run the program:
var ts = new TaskService();
var task = ts.FindTask("mainTVMTask2");
task.Run();
The nugget package used was:
TaskScheduler by David Hall
This last code is being used right now to keep an app running, the service is checking if the process is in the process list, if its not, will run that task, previusly created in the Task Scheduler.
You might choose the user that will be logged in order to run the process instead of the service that will run with System Account.
The action is a standard run command to start the program that you need.
Related
I am writing a c# program and I want to run (npm install) and (npm run build) from the c# code.
I tried
public static Boolean BuildNpm()
{
Console.WriteLine("start process method?");
var proc = new System.Diagnostics.Process();
proc.StartInfo.WorkingDirectory="../../frontend/";
proc.StartInfo.FileName = "/bin/bash";
proc.Start();
//npm install
//npm run build
//exit
proc.WaitForExit();
Console.WriteLine("Done?");
return (proc.ExitCode == 0) ? true : false;
}
I was able to create a shell that ask for command and I add the commands I want but I want the commands in the program automatically.
Why do you need to run bash to run the commands? Shouldn't it work to run npm directly from your program?
public static Boolean BuildNpm()
{
Console.WriteLine("start process method?");
var proc = new System.Diagnostics.Process();
proc.StartInfo.WorkingDirectory="../../frontend/";
proc.StartInfo.FileName = "/path/to/npm";
proc.StartInfo.Arguments = "install";
proc.Start();
proc.WaitForExit();
proc.StartInfo.Arguments = "run build";
Console.WriteLine("Done?");
return (proc.ExitCode == 0) ? true : false;
}
You should add some error handling if either execution of npm fails, as well.
I want to run a gpu accelerated python script on windows using conda environment (dlwin36).
I’m trying to activate dlwin36 and execute a script:
1) activate dlwin36
2) set KERAS_BACKEND=tensorflow
3) python myscript.py
If I manually open cmd on my machine and write:"activate dlwin36"
it works.
But when I try opening a cmd from c# I get:
“activate is not recognized as an internal or external command, operable program or batch file.”
I tried using the following methods:
Command chaining:
var start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.Arguments = "/c activate dlwin36&&set KERAS_BACKEND=tensorflow&&python myscript.py";
Process.Start(start).WaitForExit();
(I’ve tested several variations of UseShellExecute, LoadUserProfile and WorkingDirectory)
Redirect standard input:
var commandsList = new List<string>();
commandsList.Add("activate dlwin36");
commandsList.Add("set KERAS_BACKEND=tensorflow");
commandsList.Add("python myscript.py");
var start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.UseShellExecute = false;
start.RedirectStandardInput = true;
var proc = Process.Start(start);
commandsList.ForEach(command => proc.StandardInput.WriteLine(command));
(I’ve tested several variations of LoadUserProfile and WorkingDirectory)
In both cases, I got the same error.
It seems that there is a difference between manually opening cmd and opening it from c#.
The key is to run activate.bat in your cmd.exe before doing anything else.
// Set working directory and create process
var workingDirectory = Path.GetFullPath("Scripts");
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
UseShellExecute = false,
RedirectStandardOutput = true,
WorkingDirectory = workingDirectory
}
};
process.Start();
// Pass multiple commands to cmd.exe
using (var sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
// Vital to activate Anaconda
sw.WriteLine("C:\\PathToAnaconda\\anaconda3\\Scripts\\activate.bat");
// Activate your environment
sw.WriteLine("activate your-environment");
// Any other commands you want to run
sw.WriteLine("set KERAS_BACKEND=tensorflow");
// run your script. You can also pass in arguments
sw.WriteLine("python YourScript.py");
}
}
// read multiple output lines
while (!process.StandardOutput.EndOfStream)
{
var line = process.StandardOutput.ReadLine();
Console.WriteLine(line);
}
You need to use the python.exe from your environment. For example:
Process proc = new Process();
proc.StartInfo.FileName = #"C:\path-to-Anaconda3\envs\tensorflow-gpu\python.exe";
or in your case:
start.Arguments = "/c activate dlwin36&&set KERAS_BACKEND=tensorflow&&\"path-to-Anaconda3\envs\tensorflow-gpu\python.exe\" myscript.py";
I spent a bit of time working on this and here's the only thing that works for me: run a batch file that will activate the conda environment and then issue the commands in python, like so. Let's call this run_script.bat:
call C:\Path-to-Anaconda\Scripts\activate.bat myenv
set KERAS_BACKEND=tensorflow
python YourScript.py
exit
(Note the use of the call keyword before we invoke the activate batch file.)
After that you can run it from C# more or less as shown above.
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.Arguments = "/K c:\\path_to_batch\\run_script.bat";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.WorkingDirectory = "c:\\path_to_batch";
string stdout, stderr;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
stdout = reader.ReadToEnd();
}
using (StreamReader reader = process.StandardError)
{
stderr = reader.ReadToEnd();
}
process.WaitForExit();
}
I am generating the batch file on the fly in C# to set the necessary parameters.
If this is gonna help anyone in the future. I found that you must run the activation from C:\ drive.
I´m trying to create a small console app in c#. I want to run the program and save all pending changes in TFS to a .txt file. But I cant get the arguments to work. Can someone help me?
Here is my code i haved done so far:
string argument = "#tf.exe status /collection:http://tiffany:8080/tfs/ /user:* /format:detailed >c:\\Status\\Detailed.txt";
try
{
Process process = new Process();
process.StartInfo.Arguments = "#call" + " " + "C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\Tools\\VsDevCmd.bat";
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Verb = "runas";
process.StartInfo.Arguments = argument;
process.StartInfo.CreateNoWindow = false;
process.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
aI'm not really sure that I understand what you're trying to call, exactly.
Let's assume you want to run the following command line from a C# application, as if you would call it from a command line:
tf.exe status /collection:http://tiffany:8080/tfs/ /user:* /format:detailed >c:\\Status\\Detailed.txt"
I would use this code:
string arguments = #"/C tf.exe status /collection:http://tiffany:8080/tfs/ /user:* /format:detailed >c:\\Status\\Detailed.txt";
this.process = new Process();
this.process.StartInfo.FileName = #"cmd.exe";
this.process.StartInfo.Arguments = arguments;
this.process.Start();
Edit:
If that's all your console app does, why not consider creating a batch (.BAT / .CMD) file instead of a C# application?
Instead of running a command line tool you could leverage the TFS API.
There are many articles out there, e.g. Code project article on topic
and
Sample code directly from the MSDN
I suppose you have to read standard error and output from process started:
Process process = new Process();
process.StartInfo.Arguments = #"status PATH /recursive";
process.StartInfo.FileName = "tf.exe";
process.StartInfo.CreateNoWindow = false;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
var st = process.StandardOutput.ReadToEnd();
var err = process.StandardError.ReadToEnd();
But parsing tf output is not easy and I'd like to suggest to use TFS API as #Mare said
You do not need to create an application in C # to save in a text file. Just use the parameters (...) > [file name].txt at the end of the command.
The ">" symbol send the result of any command to a file.
I have a windows service which is writing in C#.
When I start debug the program it is working without any problem. But if I publish it does not work and I am not getting any error in my log file or eventviwer.
I checked the UAC to never notify.
Also my code is like this:
using (Process tvProcess = new Process())
{
tvProcess.StartInfo.WorkingDirectory = installationPath;
tvProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
tvProcess.StartInfo.UseShellExecute = true;
tvProcess.StartInfo.FileName = TVAppFileName;
bool started = tvProcess.Start();
tvProcess.WaitForInputIdle();
Logger.TraceFormat("TV - TV was started from the path {0}. Status : {1}",
System.IO.Path.Combine(installationPath, TVAppFileName),
started);
}
Also my installationPath = #"C:\Program Files (x86)\TeamViewer\Version8\"
TVAppFileName = "TeamViewer.exe"
How can I start this process without debug?
Thanks
This question could be a can of worms, but I've always wondered if it were possible to invoke an executable application from inside a web application on the web server?
I can easily set this up as a scheduled task to run and check every few minutes, but it would be nice to be able to invoke the application on demand from the a web page.
The site is an ASP.NET 2.0 website using C# and the application is an executable console app written in C#.
You need to start a new process. This is an example how to do it.
Process proc = new Process();
StringBuilder sb = new StringBuilder();
string[] aTarget = target.Split(PATH_SEPERATOR);
string errorMessage;
string outputMessage;
foreach (string parm in parameters)
{
sb.Append(parm + " ");
}
proc.StartInfo.FileName = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = sb.ToString();
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : (int)TimeSpan.FromMinutes(timeout).TotalMilliseconds //Per SLaks suggestion. Thanks!
);
errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();
outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
A link to MSDN:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(VS.71).aspx
You'll also need to check to make sure that the account the Web application is running under has the appropriate permissions to execute the program.
Process.Start
I think you could do that using the following code.
Process p= new Process();
p.StartInfo.WorkingDirectory = #"C:\whatever";
p.StartInfo.FileName = #"C:\some.exe";
p.StartInfo.CreateNoWindow = true;
p.Start();
where the Process type is from the namespace System.Diagnostics.Process