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.
Related
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.
I am trying to print a PDF using ASP (C#) through Adobe Reader -the problem is it does work on my local machine but not on server. On my local it starts Adob eReader in minimized state and I can see the file present inside Printer's "See what's printing" window. But on the server I can see the process has started from Task Manager but there's no UI visible as well no file in printer's list.
I though it may be a permission issue but after trying the following steps - it still does not work.
What I have tried.
As by default it runs under DefaultAppPool user - so I created a new App pool under the admin user, it now starts the process under admin but still I can't see the UI and no output on printer.
I added permission "Allow service to interact with desktop" to IIS Admin Service following this article https://support.microsoft.com/en-us/help/555134 - but no difference.
My current code
string args = string.Format("/s /o /h /t \"{0}\" \"{1}\"", filepath, printerName);
var startInfo = new ProcessStartInfo {
FileName = Properties.Settings.Default.AdobeReaderPath,
Arguments = args,
CreateNoWindow = true,
ErrorDialog = false,
UseShellExecute = false,
Verb = "print",
WindowStyle = ProcessWindowStyle.Minimized,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
var process = Process.Start(startInfo);
In the Application Pool Advanced settings, make sure you set the option
"Load User Profile" to True on the server.
I have program pro1.exe that reads from input file, calculates result and writes it to output file.
Now I'm writing program test.exe, that tests it on different tests (fill input, run pro1 using Process.Start() and compares output with supposed)
Problem is following: after executing pro1.exe output file is empty. However, if I run it manually, it writes to output file.
Here is code how I execute pro1:
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = _applicationName;
processInfo.ErrorDialog = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
Process proc = Process.Start(processInfo);
_applicationName is a full path to exe file.
in debug I see, that process is starting, and ending without errors.
This is often caused by having a different WorkingDirectory. You likely need to set the WorkingDirectory property to match the executable's path.
Without this, when UseShellExecute == false, the working directory may not be the application's local path.
I need to execute a process in c:\. When I use Process.Processstartinfo it doesn't execute from c:\ and so its dependencies can't be found. It runs in my app's directory instead. How can I run it in the c:\ directory?
Have you set the WorkingDirectory?
process.StartInfo.WorkingDirectory = #"MyWorkingDirectoryPath";
e.g.:
var psi = new ProcessStartInfo();
psi.WorkingDirectory = #"MyWorkingDirectoryPath";
// set additional properties
Process proc = Process.Start(psi);
When the UseShellExecute property is false, gets or sets the working
directory for the process to be started. When UseShellExecute is
true, gets or sets the directory that contains the process to be
started.
Set ProcessStartInfo.WorkingDirectory to the working directory of the process you want to launch, i.e. in your case "C:\".
I am trying to run a Batch file from .net/c# using System.Diagnostics.Process. Somehow it does not execute xcopy command of the Batch file.
Sample Batch File:
#copy test to test2 including sub directories
xcopy c:\test\ c:\test2
C# code:
public void RunMSIBatchFile(string _workingDirectory, string batchFileName)
{
var process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
WorkingDirectory = _workingDirectory,
FileName = _workingDirectory + batchFileName,
CreateNoWindow = true,
RedirectStandardError = true
}
};
process.OutputDataReceived += ProcessOutputDataReceived;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit(Convert.ToInt32(CommandTimeOut.TotalMilliseconds));
}
If I change UseShellExecute to true then it works but then there seems to be no way to capture standard output.
Has anyone faced such problem?
I've tested your exact code, and appear to be able to receive data just fine. However, since the read occurs asynchronously, it is possible for WaitForExit(...) to return before you have read all of the data. It appears that the end of the data is signalled by the Data property of the DataReceivedEventArgs passed to the OutputDataReceived event handler being null.
It is also worth noting that if xcopy requests input from the user (e.g. in the case of a file with the same name existing in the destination) it appears that no data is returned. You may want to check for this in your batch file, or also handle data from the Standard Error stream.