I have windows forms application wich runs another console application
here is the part of code
prog = new Process();
prog.StartInfo.FileName = exefile;
The console application should create file but when running that application from C# it doesn't creates any file
when im running console application with double click it works fine
here is the part of code from "exefile" (its on c++)
freopen("file.in","r",stdin);
freopen("file.out","w",stdout);
printf("somedata\n");
"file.in" surely exists
The most likely thing is that you need to set the working path:
prog.StartInfo.WorkingDirectory = ...
i.e. I'm thinking it can't find file.in in the current app folder.
You need to add this line whenever you want to start the process:
prog.Start();
Here is the link to the MSDN page for Process.Start. There are several overloads that you may want to consider.
I would suggest,
handle exceptions to see what's going wrong
like mentioned before make sure you
call the start() method
Here's a snippet of code from msdn, that you might want to refer
Process myProcess = new Process();
try
{
// Get the path that stores user documents.
string myDocumentsPath =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
myProcess.StartInfo.FileName = myDocumentsPath + "\\MyFile.doc";
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
catch (Win32Exception e)
{
if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
{
Console.WriteLine(e.Message + ". Check the path.");
}
else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
{
// Note that if your word processor might generate exceptions
// such as this, which are handled first.
Console.WriteLine(e.Message +
". You do not have permission to print this file.");
}
}
Related
I have two applications First one detects the USB/Portable HDD plugging in to the system, and this application then passes the detected Drive letter to another External application and External application ejects it.
The external application is always run as an administrator. It is working properly.
But there is an issue when "Do you want to run this application as admin YES/NO" popup appears, If I select Yes it works properly. Now If I select No even then the USB drive appears to be in use by First application and cannot be ejected manually.
My Code is given below
ProcessStartInfo start;
Process exeProcess = null;
try
{
start = new ProcessStartInfo();
start.Arguments = #"H:\";
start.Verb = "runas";
start.FileName = "Eject.exe";
start.WindowStyle = ProcessWindowStyle.Normal;
start.CreateNoWindow = false;
using (exeProcess = Process.Start(start))
{
exeProcess.WaitForExit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
The Console output in the catch block shows the message "The operation has been canceled by user" but still the resource is in use.
Kindly guide me how to tackle this issue.
I have a scenario where i would like to compress my folder due to presence of large number of files present in them using SSIS 2008. Consider it like i have one Source Folder and one Target Folder and while moving files from "SRC" to "TGT" the folder must be compressed in destination.Now feasible option for doing this i think is SSIS Script task ,since I cannot use Execute Process task due to restriction of using any third party software like 7z/Winrar etc.But i am not able to implement this even after using SSIS Script Component.Tried many online solutions but it did not work.How can i implement such thing using SSIS 2008?
You can use the ZipPackage class if you are targeting .Net 3 and above. Complete example here:
https://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx
There is also a ZipArchive class, example here:
https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx
I did this exercise , I created a Script Task to perform compression of a folder by using the compression provided by Windows;
the folder name can dynamically change.
In this way it is not necessary to use third party software like 7z/Winrar etc..
You need to provide to the Script Task the folder to be zipped and the name of the compressed folder as ReadOnlyVariables (to be added in the tab ReadOnlyVariables)
These two variables must be defined in the Variables tab (String type) of the package and can be changed dynamically through a cycle (eg. for each)
I use these two variables:
sFolderCompressed - the folder '.zip' that you want to obtain eg. \\XX.XX.XX.XX\C$\.....\folderCompressed
sFolderSource - the source folder containing the files affected eg. \\XX.XX.XX.XX\C$\.....\folderSource
(*)
The script is made using c#, choose Script Language: Microsoft Visual C# 2008
This is the code to be added in the Main method:
public void Main()
{
// TODO: Add your code here
try
{
// variables used in process
string l_sFolderCompressed = (string)Dts.Variables["User::sFolderCompressed"].Value;
string l_sFolderSource = (string)Dts.Variables["User::sFolderSource"].Value;
string l_sCommand = "zip -j " + l_sFolderCompressed + " " + l_sFolderSource + "/*";
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/C " as the parameters.
// Incidentally, /C tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/C " + l_sCommand);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Possibly display the command output.
}
catch (Exception objException)
{
Dts.TaskResult = (int)ScriptResults.Failure;
// Log the exception
}
Dts.TaskResult = (int)ScriptResults.Success;
}
You can also manage a single file
"cmd", "/C zip -j c:\\...\file.zip c:\\..\file.txt");
I hope can help
no error. no exception. Second and Third produce a file f[1]/[2]. but not first. why? I verify using debug that the command is good. and using the command I capture from debug , cut and past to command line, I can produce the file[f0].
string[] f = new string[4];
f[0] = "SNICKER.reg.txt";
f[1] = "SNDIS.reg.txt";
f[2] = "SNICS.reg.txt";
f[3] = "Ssmf.xml";
//First
Run_Process("REG", "EXPORT HKEY_LOCAL_MACHINE\\SOFTWARE\\sridge\\Snicker " + f[0] + " /y");
//Second
Run_Process("REG", "EXPORT HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNDIS " + f[1] + " /y");
//Third
Run_Process("REG", "EXPORT HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SClass " + f[2] + " /y");
private static void Run_Process(string exe_name, string arg)
{
Process myProcess = new Process();
try
{
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = exe_name;
//myProcess.StartInfo.Arguments = "/C getLH.exe > feed.txt";
myProcess.StartInfo.Arguments = arg;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
myProcess.WaitForExit();
}
catch (Exception ep)
{
Console.WriteLine(exe_name + " " + arg + ". Error: " + ep.Message);
}
}
When your app runs on a 64bit OS and you try to access the registry you could end up reading the values in the wrong folders.
This happens when you compile for x86 Platform, and thus your code is emitted as 32bit code.
In this scenario the registry redirector kicks in and changes your hand made registry paths that point to folders inside HKLM\SOFTWARE to HKLM\SOFTWARE\Wow6432Node.
The reasoning behind this behavior is complex and you could try to read something here
Said that, I still cannot understand really well what happen when we put in this scenario the REG program executed as a process launched from an application built with AnyCPU. This application should be executed as a 64bit code but, for some reason, the REG program executed is the 32 bit version (yes, there are two version of REG.EXE, one in system32 and one in SysWow64) and this version search your data in the wrong path. Perhaps this is related to the current value of the PATH environment variable.
As a side note. One of the worst decision ever made by Microsoft is to allow applications to store their configuration data in the registry. I really suggest to change this behavior, if possible
UPDATE
I can confirm that on a 64bit OS, a console application compiled as AnyCPU running the code that executes the REG.EXE command as above launches the 32bit version of REG.EXE from the WINDOWS\SYSWOW64. I have checked with ProcMon and I cannot explain why this happens. It is not related to the PATH env variable because I have only the path to C:\WINDOWS\SYSTEM32
Check out Process.start: how to get the output? and try to use that method to see the output of your command. I don't think there will be any exception, because it will only catch the exception of that block of code, not the exception of outside program that you attempt to run.
Hoping this question will get answered. Basically I am attempting to open an executable file from within an application I have created which runs on windows ce5 on a unitech barcode scanner using the .net compact framework 3.5. I have included a snippet of code where I attempt this.
Each time I debug the app via VS2008 I am getting a Win32Exception but with no further details (with or without the try catch statement). It does not tell me what the exception is nor does it provide an error code.
Here is the code I am using to try to start the process. Can you see anything wrong with it that may be causing an error? I have double and triple checked the filename and also the directory where it is stored so it is not that.
private void CustomButtonEvent(object sender, EventArgs e)
{
string buttonName = ((Control)sender).Name;
ProcessStartInfo processStartInfo = new ProcessStartInfo();
buttonName = buttonName.Remove(0, 3);
buttonName = buttonName.Replace(' ', '_');
switch (buttonName)
{//todo need to open the different exe's here
case "End_Of_Line":
{
MessageBox.Show(#"No app behind this button yet.");
break;
}
case "Asset_Tracking":
{
processStartInfo.FileName = "AssetTrackingScanner.exe";
processStartInfo.WorkingDirectory = #"\Flash Storage\CompoundingManagementScannerSuite\Applications\AssetTrackingScanner\AssetTrackingScanner\bin\Debug";
try
{
Process.Start(processStartInfo);
}
catch (Exception f)
{
MessageBox.Show(f.ToString());
}
break;
}
case "Stock Take":
{
MessageBox.Show(#"No app behind this button yet.");
break;
}
case "Despatch":
{
MessageBox.Show(#"No app behind this button yet.");
break;
}
}
}
I see two problems. First, CE requires fully qualified paths, so the processStartInfo.FileName should be something like this
processStartInfo.FileName =
#"\Flash Storage\CompoundingManagementScannerSuite\Applications\AssetTrackingScanner\AssetTrackingScanner\AssetTrackingScanner.exe";
Second, CE has no concept of a WorkingDirectory, so remove the call to set it.
I'm also a little concerned about the \bin\debug\ part of your path. Studio doesn't deploy to a bin\debug\ folder on the device. It build to one on the PC, but on the target device the only way it would be there is if you manually set it. This leads me to think you need to check your on-device applicatin path.
When I execute an exe file (PVFProject15.exe), it reads the data from an input file (inputFile.txt) and print the results in another file (outputFile.txt). The exe file works well when I double click it; It opens the console window which stays opened until the output file is created. However, when I run (PVFProject15.exe) from c#, the console window opens and closes very quickly and the output file is never created.
I would really appreciate your help since I have been working to fix this for a whole day and never found the answer. Here is my code below.
private void button1_Click(object sender, EventArgs e)
{
Process runFortran = new Process();
try
{
runFortran.StartInfo.FileName = "C:\\temp\\trial\\PVFProject15.exe";
runFortran.Start();
runFortran.WaitForExit();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Thank you in advance.
Safaa
Probably PVFProject15.exe needs current directory to be set to C:\temp\trial
If PVFProject15.exe writes to file using relative path, look for outputFile.txt in directory from which you start your main program-bootstrapper.
I also meet with same problem, when I try start some .exe and .hta from my C# based software.
I start to looking for solution and answer of Mike Mozhaev get to me right direction.
In your code you need to use:
StartInfo.WorkingDirectory = Convert.ToString( System.IO.Directory.GetParent(appPath));
So code have to be like this:
if (File.Exists(appPath))
{
Process runProcess = new Process();
runProcess.StartInfo.WorkingDirectory = Convert.ToString( System.IO.Directory.GetParent(appPath));
runProcess.StartInfo.UseShellExecute= true;
runProcess.StartInfo.FileName = appPath;
runProcess.Start();
}