Pass path with spaces to Fortran application - c#

I have an old Fortran application to which I'd like to pass a path to a file.
Unfortunately my path contains spaces. I cannot change the file path but I'd like to process the file with my Fortran application.
The Fotran app doesn't work even if I pass the path from C# with quotes (e.g. "C:\Users[username]\Desktop\Example Path\example_file.dat").
This is my code:
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = #"/c <program_name> <file path with spaces>",
WorkingDirectory = #"C:\Users\<username>\Desktop\<exe_location>\",
UseShellExecute = false,
CreateNoWindow = true
};
This is the error, stopping at the first space:
Non existent file: <file p
It's the same if I try to pass the path via command line.
Is there some escape sequence I'm missing? Thank you in advance.

Related

Run Python script with imports in C#

Lets say I have this super Python script that needs to run cv2 in the future...
import cv2
def method():
print("Hello")
parameter = "l"
return "OOPS"
method()
And in C# something like this.
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"D:\Programming\Python\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
But this does throw an error "ImportError: DLL load failed". Alright seems like it is lookin in wrong directories for libraries since I have about 4 Python interpreters. Follows quick fix.
string path = #"D:\Programming\Python;" + Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PATH", path, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONHOME", #"D:\Programming\Python;", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONPATH ", #"D:\Programming\Python\Lib; D:\Programming\Python\DLLs", EnvironmentVariableTarget.Process);
string fileName = #"..\Python\hello.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"D:\Programming\Python\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
Import DLL is fixed now, but another wild bug appeared named,
Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'
At this point I am lost and dont know what should I do next... any ideas are welcome, have a nice day.
UPDATE:
Deleted all other python interpretors aside from anaconda and one virtual env and tried following:
Run Python script from Visual Studio Code with given interpretor, works fine.
Run it from Anaconda prompt, aswell.
Added manually to system environment variables
PATH=D:\Programming\Python
PYTHONHOME=D:\Programming\Python
PYTHONPATH=D:\Programming\Python\Lib;D:\Programming\Python\DLLs;D:\Programming\Python\Lib\site-packages
So now I can successfully call "python" from cmd, like that and check version, the virtual env is python 3.6 and this is the right one.
Python is correct
But this is where all the fun begins you would expect "hello" in your console...
hell incarnate
Did not find correct answer to this problem, but discovered workaround in p2exe or pyinstaller.
Simply call pyinstaller.py --onefile xx.py and create exe file and pass that into process.

Unable to execute cmd command using C#

I have been trying to invoke below cmd command from C#, but it didn't worked and I got wrong path error. Although it is working if I execute it directly from CMD:
CMD Command: C:\Program Files (x86)\ABC Client>xyz.exe /launch "Your Software 12.7"
I tried below code:
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd")
{
WorkingDirectory = #"C:\Windows\System32",
Arguments = "/C \"\"C:/Program Files (x86)/ABC Client/xyz.exe\"\" /launch 'Your Software 12.7'",
RedirectStandardOutput = true,
RedirectStandardError = true,
WindowStyle = ProcessWindowStyle.Normal,
UseShellExecute = false
};
Process process = Process.Start(processStartInfo);
You need to escape the quotation marks.
This question is about escaping quotation marks
string softwareName = "\"Your Software 12.7\"";
This should do the trick.
Finally fixed: The correct string will be:
Arguments = "/C \"\"C:/Program Files (x86)/ABC Client/xyz.exe\" /launch \"Your Software 12.7\"\"";
Thank you everyone for your inputs :)
If the problem is just the string to be executed, i think this outputs just what you want:
Arguments=#"C:\Program Files (x86)\ABC Client\xyz.exe /launch ""Your Software 12.7""";
Either of the following should work:
Arguments = #"/C ""C:\Program Files (x86)\ABC Client\xyz.exe"" /launch ""Your Software 12.7""";
Arguments = "/C \"C:\\Program Files (x86)\\ABC Client\\xyz.exe\" /launch \"Your Software 12.7\"";
That is, double quotes around the program location (you had double quotes twice instead of once), back slashes instead of forward slashes, and double quotes around the "Your Software 27.7".
Using a string literal (# prefix) you need a double quote before each double quote in the final string. Without the # prefix, you need a back slash before each back slash and double quote in the final string.

how to give address of parts to copy command in c#

when i run copy command in my c# code it produce no error or exception because it is not finding the parts path i do not know how to give full directory path or path of every part which i am joining.actually i am merging file parts to a single file using coy/b by using this code...
string strCmdText;
strCmdText = "/C copy/b test.txt.10485760.0000.part" +
"test.txt.10485760.0001.part" +
"test.txt.10485760.0002.part" +
"test.txt.10485760.0003.part" +
"test.txt.10485760.0004.part" +
"test.txt.10485760.0005.part test.txt";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
You can specify the path of your files as the working path of the process. For example:
var startInfo = new System.Diagnostics.ProcessStartInfo
{
WorkingDirectory = #"THE\PATH\OF\FILES",
WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal,
FileName = "cmd.exe",
Arguments = "YOUR COMAND HERE";
};
Process process = Process.Start(startInfo);
For your command, note that you can copy all files into one using a wildcard for the parts:
copy *.part test.txt
/b is for binary data, so i think is not needed in your case.
You can also set other properties for a process, for more info check the doc: ProcessStartInfo.
For such a complex task, I would use the process as a bash rather then just an execution tool.
Create a Process
Redirect it's streams (Input, Output)
With a StreamReader and StreamWriter u can now access the cmd
Now just control it the way u need it, like setting the working directory to the path and do ur command.
If this is not what u want, u can allways set the working directory on the ProcessStartInfor -> Link

Calling ProcessStartInfo with a path with spaces always breaks

I'm calling a command line program with the following configuration:
var processStartInfo = new ProcessStartInfo {
FileName = mainCommand,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
And when I'm running it with mainCommand being a path that has no spaces it always works, if there is a space on the path to the command it fails with:
Could not find the command file at C:\Users\Some
Where the actual path would be:
C:\Users\Some User\AppData\Local\Temp\Process.exe
So, why isn't it being escaped and is there a way I can escape this path name to prevent this error?
Try wrapping it with quotes:
string targetExe = "\"C:\\this path with spaces\\helloWorld.exe\"";
It works like such, but it also work without having to worry about it as Patrick Hofman said. Something's different on your system it seems.
If you want to pass arguments, do it trough Arguments in ProcessStartInfo. Obviously, if these have spaces too (ie: /arg1 "An Argument"), you will have to wrap them in quotes as above.

Executing batch file in WCF

I am trying to execute a batch file server-side in IIS to add a printer using the printuientry call.
The problem I am facing is that I am using the Copy To Output Directory - Copy Always and the following code:
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
var processInfo = new ProcessStartInfo(Path.Combine(path, "AddPrinter.bat"))
{
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = path,
Arguments = ipAddress,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
var process = Process.Start(processInfo);
process.WaitForExit(10000);
process.Close();
Now when deugging, I have checked the values of path and its set to
file:\C:\_Projects\PrinterServerV2\bin
and I have checked to see if the file and directory exist which they do.
But I get the exception:
System.ComponentModel.Win32Exception (0x80004005): The directory name is invalid
Any ideas please??
Check if the user you had set in the iis configuration does have all privileges to run, access, write and read what you wanna do with your batch file.
Also try to change your ProcessStartInfo like the process will be cmd.exe and your batch file the argument.
I had a similar issue How to execute multiples .BAT files in C#
try AppDomain.CurrentDomain.BaseDirectory as path.

Categories

Resources