Can't Use tskill from C# - c#

I have a C# program. It is literally one line:
System.Diagnostics.Process.Start(#"C:\ProgramData\task manager\killtask.vbs");
There is a VBS file there, which generates a batch file that allows you to type a command and it will be executed and closed. It then sends the following keys: "tskill /a notepad {ENTER}". I know that's probably the worst practice you've ever seen, but bear with me.
When the VBS file is run by hand, it successfully closes notepad. When it is run through C# using the above line, it prints "tskill is not recognized" etc. before it closes.
Why is it that I can't use tskill through batch via VBS via C#, but I can use it just through batch via VBS? Remember, both clicking on it and running my C# code successfully ATTEMPT to kill notepad, but only clicking on it by hand closes notepad successfully.

You probably need to set the working directory. Without it your program will be executed from the directory of the process that starts your script and this directory is not the correct one.
Juse try with
var processStartInfo = new ProcessStartInfo();
processStartInfo.WorkingDirectory = #"C:\ProgramData\task manager");
processStartInfo.FileName = "killtask.vbs";
Process proc = Process.Start(processStartInfo);

Related

Run an External Program or Batch File From a C# Xamarin Program

I want to have my C# (Xamarin) program run an EXE or batch (BAT) file. The user will be running my program, and will click on one of several buttons, some of which open Web pages and others of which run external programs. These files will be on the same computer as the one running the main program and don't need greater permissions. The overall program will be in Windows, UWP.
I already have code to pull info from the database saying "the button the user clicked references a program and it's (eg) C:\Tools\MyTool.exe". (Real path more like (C:\Users\Me\source\repos\ProductNameV2\ProductName\ProductName.UWP\Assets\EXE\whatever.exe".) I used a "demo.bat" file containing nothing but echo and pause statements, or references to a built-in Windows program like Notepad or Calc that an ordinary command prompt can recognize without an explicit path (ie. that's part of the recognized system Path). Yes, the real path to the dummy file does exist; I checked. I've also explicitly added files demo.bat and dummy.txt to my C# project.
Here's roughly what I've tried so far to actually run a batch file, or an EXE, or just to try opening a text file. Nothing works.
1)
bool check = await Launcher.CanOpenAsync(#"file:///C:\Tools\demo.bat"); // Returns false.
bool check = await Launcher.CanOpenAsync(#"file:///C:\Tools\dummy.txt"); // Returns true.
await Launcher.OpenAsync(#"file:///C:\Tools\demo.bat") // Seems to do nothing; silently fails.
await Launcher.OpenAsync(#"file:///C:\Tools\dummy.txt") // Same.
2)
Process batchProcess = new Process();
batchProcess.StartInfo.FileName = #"file:///C:\Tools\demo.bat"; // Same result with notepad.exe
batchProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
batchProcess.Start();
batchProcess.WaitForExit();
// Result: "Access is denied" error during Start().
3)
var otherProcessInfo = new ProcessStartInfo(#"file:///C:\Tools\demo.bat")
var otherProcess = Process.Start(otherProcessInfo);
otherProcess.WaitForExit();
otherProcess.Close();
// Result: "The system cannot find the file specified" despite it being the same path as in previous examples.
// Also tried literally using the path C:\Tools\demo.bat, without adding that to the C# project.
// One thing that slightly works is to use:
var otherProcessInfo = new ProcessStartInfo("cmd.exe", "/c echo Hello world!");
// This version opens a window and instantly closes it again. With "/c pause" instead, it opens, saying "press any key to continue".
// Chaining multiple commands with newline or semicolon characters doesn't work as a form of batch file.
So: the only tiny success I've had here is to run cmd.exe, to run a one-line command. I suppose that depending on what the batch file must do, there's some possibility of receiving a string, breaking it into lines, then running cmd.exe using method 3 to call them one at a time. Which is ugly at best.
Is there some better way to do this -- to run a batch file or an EXE from within my program?
EDIT: Yes, I did in fact look at documentation before asking. Why did I use URIs? Because of multiple errors telling me that the simple path strings ("C:\this\that") I was using were in an "Invalid URI format". Using Process.Start("notepad.exe") silently fails, doing nothing. Using a method involving System.Diagnostics.Process (found at How to run external program via a C# program? and yes I saw that before) fails with an error of "Access denied" when using my batch file reference, or silently failing (no window opens) using plain old notepad.exe. I avoided setting Process options that say hide the window.
So to rephrase: Is there a way to make my program run some EXE somewhere on the computer, or to run a batch file that has more than one command in it? What is that way?
Using the data you collected, I was able to run a batch file by doing the following:
var strPathToExeOrBat = System.IO.Path.Combine("C:\\Tools", "demo.bat");
var otherProcessInfo = new ProcessStartInfo("cmd.exe", $"/c call \"{strPathToExeOrBat\"");
var otherProcess = Process.Start(otherProcessInfo);
otherProcess.WaitForExit();
otherProcess.Close();
I also think it would be helpful to review the capabilities of the cmd.exe application.
I found this post to be helpful:
https://stackoverflow.com/questions/515309/what-does-cmd-c-mean#:~:text=%2FC%20Carries%20out%20the%20command%20specified%20by%20the%20string%20and,switches%20by%20typing%20cmd%20%2F%3F%20.
In particular the /k option will leave the window open, if you don't want it to close after running a script.
Thank you very much for your question! It really helped me find the answer to this! (at least for my situation of a .NET MAUI windows app, but MAUI is built off of Xamarin.Forms, so you shouldn't have a problem doing the same thing)
EDIT: Updated to use file path from question and string interpolation with System.IO.Path.Combine for slightly greater cross platform capability

How to expand the search environment variable %ProgramData% and use the start up info

I got PythonApplication1.py into the Sources of the C# Windows Form Application. On specific condition I write it into the Program Data folder this way:
File.WriteAllBytes(#"%ProgramData%\\Folder\\PythonApplication1.py", Resources.PythonApplication1);
and then with specific condition C# runs Python Application from program data folder, this way:
Process.Start(#"%ProgramData%\\Folder\\PythonApplication1.py");
On the side of Python code I got second thing, it writes some data into the text document, which is located by the same path, but creation of it happens in Python itself, but it can be done from C# code, no matter, here:
path = (#"%ProgramData%\Folder\doc.txt")
but python code must write in this file by same program data path:
data = open (r'doc.txt', 'w')
and to write, just by same location, as both are there:
with open(r'doc.txt') as my_file:
The problem is, when I run this python code as it shown above, this way:
Process.Start(#"%ProgramData%\\Folder\\PythonApplication1.py");
It does two wrong things, which does not happens, if it is not %ProgramData% directory and located with C# .exe in debug folder, just by Process.Start("PythonApplication1.py");, or if I run Python Code inside %ProgramData%\Folder path with doc.txt, just by hand. It creates and writes directly into the file, all is correct.
Otherwise if Process.Start(#"%ProgramData%\\Folder\\PythonApplication1.py"); I got second result, it does not writes data into the doc.txt by %ProgramData%\Folder and python code creates it out of program data folder in debug folder with C# .exe.
So question is how to create and write from python code into the doc.txt located by C# Application "%ProgramData%\Folder" path.
Seems like, if PythonApplication1.py is exist inside ProgramData:
File.WriteAllBytes(#"%ProgramData%\\TAOZ\\PythonApplication1.py", Resources.PythonApplication1);
And if executed by hand it creates text document and writes to it, it must do the with Process.Start, but not.
also I tried to use star info, but not sure if this is correct, anyway I got same result:
ProcessStartInfo startInfo = new ProcessStartInfo(#"%ProgramData%\\folder\\PythonApplication1.py");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(startInfo);
So seems like I need two things here. To expand the search environment variable %ProgramData%. and also need to use the start up info to tell the process to start on that particular folder. Otherwise, the current working folder will be the same folder as application I guess, but not sure how to do it, and if it is reason of problem, need your help.
Since it's a python program, you'll have to point to the python EXE. Assuming you have the pythonpath environment variable, this ought to work:
ProcessStartInfo startInfo = new ProcessStartInfo(Environment.ExpandEnvironmentVariables(#"%PYTHONPATH%\python.exe"), Environment.ExpandEnvironmentVariables(#"%ProgramData%\folder\PythonApplication1.py"));
startInfo.WorkingDirectory = Environment.ExpandEnvironmentVariables(#"%ProgramData%\folder\");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(startInfo);

Different command prompt window behaviors

I've seen a very similar question asked before, here, however the answer thread fell apart. Basically, I installed Python (and checked the option to add to the Path variable), confirmed that it is indeed in the path variable (through the Environment Variables window like you would normally).
When opening a cmd window manually, I can type python -V and get the version back, and anything else really, and everything works fine, python is indeed exposed through the command prompt (when opened manually).
However, when I attempt to run a command through cmd.exe with a C# app I have, I get
'python' is not recognized as an internal or external command,
operable program or batch file.
The block of C# code I have
var proc = new Process();
var startInfo = new ProcessStartInfo
{
UseShellExecute = true,
FileName = "cmd.exe",
Arguments = "/K " + command
};
proc.StartInfo = startInfo;
proc.Start();
This has worked fine in the past. However I had my work machine upgraded to Windows 10 and have been struggling to get this working.
The command text hasn't changed since the application was working before my windows upgrade, and if I take it's text and run it through a manually opened command prompt it executes fine with no issues. So I'm hesitant to believe it's an issue with the command itself.
UPDATE: If I run echo %PATH% in a regular prompt I see python, if I run it in the command prompt my application opens, I do not. I tried using set PATH, but that didn't help. Why is it that the PATH variable is different between a command prompt I open manually and one my application opens?
I thought it might have something to do with User and System variables having their own path, but Python is in both of them when checked via System Properties, so I'm at a loss.

How can I capture the console output of dpinst when running silently?

I've got a process (written in C#) that runs with administrative rights and invokes dpinst.exe to perform an automated driver installation. It writes its own custom dpinst.xml file to specify things like suppressing the EULA page, suppressing the wizard, running a "quiet install," and searching in all subdirectories.
When I invoke this manually from the command line (see example below), it seems to work fine. Because of the command line switches I'm using it prints a bunch of INFO level log messages in the console.
C:\Path\To\Drivers> dpinst.exe /C /L 0x409
I want to log what gets printed in the console, so my C# code looks something like this:
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #"C:\Path\To\Drivers\dpinst.exe",
Arguments = "/C /L 0x409",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
Verb = "runas"
}
};
string output;
process.Start();
using (var reader = process.StandardOutput)
{
output = reader.ReadToEnd();
reader.Close();
}
However, when I run that code, the value of output is always blank. So, for my next experiment, I tried using the command line directly to pipe the output to a file, like this:
C:\Path\To\Drivers> dpinst.exe /C /L 0x409 > test.log 2>&1
That created the test.log file, but it was also blank. Interestingly enough I could still see all of the console output that dpinst.exe generates in that same console window; for some reason it didn't get redirected to the file that I specified. So the symptom is the same regardless of how I invoke the dpinst executable; it doesn't want to redirect output. I'm not sure what the underlying reason for that is, nor how to solve it. How can I capture the console output?
EDIT: If anyone wants a copy of dpinst.exe to run locally and test out themselves, I've provided one at this link, bundled with the dpinst.xml file I'm using. Remember that you need to invoke it with the /C command line switch in order to generate any command line output. Alternatively, if you're paranoid and don't want to download an executable from some random Stack Overflow question, you can get the dpinst.exe utility as part of the Windows Driver Kit from Microsoft. It's a free download, but you have to extract the utility (which is only 500 KB) from the full WDK ISO (which is ~700 MB). Up to you. :)
Your code runs perfectly fine with standard tools (like "ping") for example. So maybe for some reason dpinst writes to standard error instead? You can set RedirectStandardError = true and read StandardError to check if that is the case.
UPDATED in case anyone else will hit this problem:
It seems dpinst does not write to standard output but logs messages to console in some other way. Only way to achieve your goal which comes to my mind is: remember size of "%SystemRoot%\DPINST.LOG" file, run your command, wait for exit, then read everything between remembered position and end of file. This way you will get your logs.
I my answer will help other. When you run Dpinst.exe and you add the swicth /C to dump the log to console, it also creates a log file in this directory "C:\Windows\DPINST.LOG"
You can locate the log file there..

Java and .net interoperability

I have a c# program through which i am opening cmd window as a a process. in this command window i am running a batch file. i am redirecting the output of that batch file commands to a Text File. When i run my application everything seems to be ok.
But few times, Application is giving some error like "Can't access the file. it's being used by another application" at the same time cmd window is not getting closed. If we close the cmd process through the Task Manager, then it's writing the content to the file and getting closed. Even though i closed the cmd process, still file handle is not getting released. so that i am not able to run the application next time onwards.Always it's saying Can't access the file. Only after restarting the system, it's working.
Here is my code:
Process objProcess = new Process();
ProcessStartInfo objProInfo = new ProcessStartInfo();
objProInfo.WindowStyle = ProcessWindowStyle.Maximized;
objProInfo.UseShellExecute = true;
objProInfo.FileName = "Batch file path"
objProInfo.Arguments = "Some Arguments";
if (Directory.Exists(strOutputPath) == false)
{
Directory.CreateDirectory(strOutputPath);
}
objProInfo.CreateNoWindow = false;
objProcess.StartInfo = objProInfo;
objProcess.Start();
objProcess.WaitForExit();
test.bat:
java classname argument > output.txt
Here is my question:
I am not able to trace where the problem is..
How we can see the process which holding handle on ant file.
Is there any suggestions for Java and .net interoperability
In situations like this I start up the Process Explorer ( by Sysinternals, awesome tool btw ) click Ctrl+F, and enter the name of the file. It will search across all running processes and will list the file handles to this file by the applications that have it open.
You can then either drop the handle, or kill the app - whatever you think is better )
You can try forking and attaching file descriptor from C# rather than launching a bat file.
I think the problem is because the java program is accessing the text file when the C# program is writing something on it, and hence a "file cannot access" problem.
If I were you, I would do everything in C#-- I won't use Java to read the state of the C# program. And I would access the file only after I've completed whatever the C# needs to do.
As for to see what process is locking up your file, you can use Process Explorer for this purpose.

Categories