Java and .net interoperability - c#

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.

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);

Can't Use tskill from 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);

If I have the URL of a torrent, how can I just "launch" it using the Process.Start()?

I found a way to obtain the URL of a torrent file, if I have this in string format, is there a way for me to just launch it whenever a user presses a button in my app?
I know I could save the file and then call it up, but I'd rather just open it. Is this possible?
You can just start it, but what will happen then is your default browser will open and it will download the file. And depending on the local settings on that machine it will do the default thing.
I would not recommend this method, it means the end user will have to do alot of extra steps. And the different browsers behave differently, and may not obey windows file extentions ( thing firefox )
If your doing this inside a application you should download it yourself, you can read about that here. .NET Frameworks offers great solutions to download the file yourself.
Also if you do it via Proccess you will not get a refere when downloading, some sites may then block you to stop hot linking. but if you control the download class you can send a refere url
Don't know if this is OK for you, but if you have the torrent protocol registered to an installed application, simply launching the URL as if it were the path of an executable file (for example by using the Process class) will launch the associated application. See here: http://kb.mozillazine.org/Register_protocol
Try this:
Process p = new Process();
p.StartInfo.FileName = "http://domain/folder/file.torrent";
p.Start();
Or, if you like one-liners:
new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "http://domain/folder/file.torrent"
}
}.Start();
That will call your default browser to download that file and tries to open it. Clicking "Open" you associate program takes control.

From C#, open an arbitrary application

Related question [stackoverflow] here.
I'm trying to do the above, but I want to take the process one step further. I want to open an arbitrary file using the default editor for the file type. From that point, I want to allow my user to interact with the file as they would normally, or continue to work in my application. The extension is what happens after the user finishes editing. Is there a way I can capture a close (and ideally save) event from the external application and use that as a trigger to do something else? For my purposes, tracking the closing of the external application would do.
I can do this in the specific case. For example, I can open a Word instance from my application and track the events that interest my application. However, I want to de-couple my application from Word.I want to allow my users to use any document editor of their choice, then manage the storage of the file being edited discretely behind the scenes.
You can do this in a manner similar to the referenced question, but the syntax is slightly different:
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo =
new System.Diagnostics.ProcessStartInfo("C:\...\...\myfile.html");
process.Start();
process.WaitForExit(); // this line is the key difference
The WaitForExit() call will block until the other application is closed. You would use this code in a separate thread so that the user can keep using your application in the meantime.
Use the FileSystemWatcher class to watch for changes to the file.
EDIT: You can also handle the Exited event of the Process object to find out when the program is exited. However, note that that won't tell you of the user closes your file but doesn't exit the process. (Which is especially likely in Word).
To listen for file change, you can use the FileSystemWatcher and listen for a change in the last modified date.
You can also monitor the process and check then file when the process close.
I found this useful tip online just now. It seems to be what you are looking for. This article (link broken) has some more detail and useful, to-the-point tips on C# programming.
string filename = "instruction.txt";
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(#filename);
System.Diagnostics.Process rfp = new System.Diagnostics.Process();
rfp = System.Diagnostics.Process.Start(psi);
rfp.WaitForExit(2000);
if (rfp.HasExited)
{
System.IO.File.Delete(filename);
}
//execute other code after the program has closed
MessageBox.ShowDialog("The program is done.");

Categories