I have an .exe file which was written in C. It is a command line application. I want give command line and also get correspond output in this application through a C# application.
How do I invoke the command and get the output from C#?
You could use the Process.Start method:
class Program
{
static void Main()
{
var psi = new ProcessStartInfo
{
FileName = #"c:\work\test.exe",
Arguments = #"param1 param2",
UseShellExecute = false,
RedirectStandardOutput = true,
};
var process = Process.Start(psi);
if (process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
{
var result = process.StandardOutput.ReadToEnd();
Console.WriteLine(result);
}
}
}
You need to use the Process.Start method.
You supply it with the name of your process and any command line arguments and it will run the executable.
You can capture any output which you can then process in your C# application.
Related
So I am witting a java program for interacting with filesystem.
Java program itself cannot run as super user. I created a special user for this program and gave it some special privileges to run some commands without password (via visudo file).
So I I'd like to check if a file exist. I used:
if(f.exists() && !f.isDirectory()) but the problem is this fails if I am checking if files exist that is read/write protected or if it belongs to another user.
That is why I need to use bash. for example, when I am retrieving information about file I use the following:
String[] command = new String[] { "sudo", "stat", filepath, "-c", "%F##%s##%U##%G##%X##%Y##%Z" };
process = runtime.exec(command); and then just parse the output.
For example moving a file I use this:
String[] command = new String[] {
"sudo",
"-u",
user,
"mv",
source,
target
};
So now I am looking for a way to get simple true/false response when checking if file exist.
I think I could use find command or something similar?
I've solved my issue by using the following command:
String[] command = new String[] { "sudo", "-u", user, "test", "-f", path };
Where user is user who I am running command as. And path is the path-to-file we are testing.
I then read the execute and read command's output in the code below.
I hope it helps someone someday...
process = runtime.exec(command);
errbr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((messageLine = errbr.readLine()) != null) {
message += messageLine + ";";
}
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((messageLine = br.readLine()) != null) {
message += messageLine;
}
As I am very new to haxe.
The following is my program in haxe where I am trying to retrieve the list of files opened in windows client. Openfiles is the command which gives the list of files opened in windows machine , which needs to be executed as an administrator. I am failing to execute the program which is giving no output.
class Hello {
public static function main() {
trace("Hello World!");
if(Sys.systemName()=="Windows"){
//var x = Sys.command("Openfiles",[]);
var output = new sys.io.Process("ipconfig", []).stdout.readAll().toString();
trace("output:::"+output);
}
if(Sys.systemName()=="Linux"){
//var x = Sys.command("Openfiles",[]);
var output = new sys.io.Process("ifconfig", []).stdout.readAll().toString();
trace("output:::"+output);
}
}
}
How to execute Openfiles system command as an administrator ?
for Linux you can do this:
var output = new Process("bash", ["-c 'echo rootS_PASswoRd | sudo -S ifconfig'"]).stdout.readAll().toString();
trace("output:::"+output);
I'm building a logging module that can be called by multiple callers located in different files.
My objective is to initialize the log file at the start of program and have the callers just call a function that logs to the file initialized earlier without going through the whole initialisation again.
I can't quite grasp the concept of module exports hence I'm hoping that you can help.
The actual logging occurs on the method write. On the main app.js file, I can initiate and log just fine.
However on a different file, I'm having a mental block on how I can just log to the file without going through creating the logfile again.
var fs = require('fs');
var fd = {},
log = {},
debug = false;
var tnlog = function(env, file, hostname, procname, pid) {
if (env == 'development')
debug = true;
fd = fs.createWriteStream(file, { flags: 'a', encoding: 'utf8', mode: 0644 });
log = { hostname: hostname, procname: procname, pid: pid };
};
tnlog.prototype.write = function(level, str) {
if (debug)
console.log(str);
else {
log.timestamp = Date.now();
log.level = level;
log.str = str;
fd.write(JSON.stringify(log) + '\n');
}
};
exports.tnlog = tnlog;
This is how I initialize and logging on the main file:
var logfile = '/var/log/node/www/app.log';
var tnlog = require('./lib/tnlog').tnlog,
log = new tnlog(app.get('env'), logfile, os.hostname(), appname, process.pid);
If you can suggest a better way of doing things, I definitely will appreciate that.
edit
The simplest solution would be to put
var logfile = '/var/log/node/www/app.log';
var tnlog = require('./lib/tnlog').tnlog,
module.exports = new tnlog(app.get('env'), logfile, os.hostname(), appname, process.pid);
into a separate file (mylogger.js), and require that anywhere you want to log something with logger = require "./mylogger.js . You always get back that single instance of tnlog, because node caches the exported value.
I also see you might be using Express, so you could also do
app.set("logger",new tnlog(app.get('env'), logfile, os.hostname(), appname, process.pid))
and retrieve it anywhere you have a reference to the app object with app.get("logger").
old
More complicated:
You must decide whether you want to support logging to different files while the same app is running. If so, you absolutely need to create an object for each log file. You don't have to export a constructor function per se, you could also export a kind of hybrid between a factory and a singleton pattern.
You would create something like:
var loggers = {}
module.exports = function getLogger(env, file, hostname, procname, pid) {
key = env + file + hostname + procname + pid)
if(loggers[key]) return loggers[key]
return loggers[key] = new Logger(env, file, hostname, procname, pid)
}
I.e. you check if you have already created the logger object, based on concatenating the function argument variables.
You then need to create a proper Logger constructor of course, but I assume you know a bit of Javascript.
Note that the loggers object will remain a private variable, just like the Logger constructor. Because node.js caches the object the module exports, the value of the loggers object will persist over multiple calls to require, as part of the getLogger closure.
Consider I want to expose a method called Print
Binding method as prototype:
File Saved as Printer.js
var printerObj = function(isPrinted) {
this.printed = isPrinted;
}
printerObj.prototype.printNow = function(printData) {
console.log('= Print Started =');
};
module.exports = printerObj;
Then access printNow() by putting code require('Printer.js').printNow() in any external .js node program file.
Export method itself using module.exports:
File Saved as Printer2.js
var printed = false;
function printNow() {
console.log('= Print Started =');
}
module.exports.printNow = printNow;
Then access printNow() by putting code require('Printer2.js').printNow() in any external .js node program file.
Can anyone tell what is the difference and best way of doing it with respect to Node.js?
Definitely the first way. It is called the substack pattern and you can read about it on Twitter and on Mikeal Rogers' blog. Some code examples can be found at the jade github repo in the parser:
var Parser = exports = module.exports = function Parser(str, filename, options){
this.input = str;
this.lexer = new Lexer(str, options);
...
};
Parser.prototype = {
context: function(parser){
if (parser) {
this.contexts.push(parser);
} else {
return this.contexts.pop();
}
},
advance: function(){
return this.lexer.advance();
}
};
In the first example you are creating a class, ideally you should use it with "new" in your caller program:
var PrinterObj = require('Printer.js').PrinterObj;
var printer = new PrinterObj();
printer.PrintNow();
This is a good read on the subject: http://www.2ality.com/2012/01/js-inheritance-by-example.html
In the second example you are returning a function.
The difference is that you can have multiple instances of the first example (provided you use new as indicated) but only one instance of the second approach.
This is just a quick question that I am sure someone will be able to answer quickly as I am most likely just missing something.
Lets say I have the following directory layout
Folder1
-> CurrentlyRunning.EXE
-> Folder2
ProcessToStart.Bat
ApplicationToStartFromBat.exe
This is the code inside the applications.
CurrentlyRunning.EXE:
var proc = new Process
{
StartInfo =
{
FileName = "Folder2/ProcessToStart.Bat",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false
}
};
proc.Start();
ProcessToStart.Bat:
START ApplicationToStartFromBat.exe
Now, if I run ProcessToStart.Bat by double clicking on it, it will open ApplicationToStartFromBat.exe with no problems (which is good). If I run CurrentlyRunning.EXE (which will execute the code I posted above) the BAT file fails saying it can't find my EXE (which is really weird).
If I change the BAT file to:
START Folder2/ApplicationToStartFromBat.exe
and then run CurrentlyRunning.EXE, the bat will then properly open ApplicationToStartFromBat.exe. My problem is I can not change the code inside the bat for one reason or another.
Why is proc.Start() causing the bat file search root directory to change, and how do I stop this from happening?
Thanks
I think it is to do with where the working directory is for your exe file.
Try using ProcessStartInfo.WorkingDirectory to set the correct directory for your batch file.
var proc = new Process
{
StartInfo =
{
FileName = "Folder2/ProcessToStart.Bat",
WorkingDirectory = "DirectoryPath";
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false
}
};
proc.Start();