Process.Start() exits right away on Windows 7 - c#

Process.Start("d:/test.txt"); //simple .txt file works perfectly fine on Windows 8 onward but on Windows 7 (x64) it starts the process and immediately closes it.
I've already tried the following:
Calling through ProcessStartInfo and setting CreateNoWindow=true, UseShellExecute=true and Verb="runas" (though not sure why I had to set this one).
Tried attaching Exit event and it confirms that the process does start but it exits right away and I don't even see the Notepad window open for a blink of a second.
Edit: I've tried it with an image files and few other extensions and they open just perfect. Something wrong with just the .txt files (and/or probably other formats).

I was able to solve this bug just by changing build platform from AnyCPU to specifically x64 (my target machine is x64). This is strange but it solved the problem! Thanks Simon Mourier for this tip.

Its definitely an issue with file association. I have tried it windows 7 and it works fine. Try double clicking on the file and check if it opens in notepad, if it doesn't then configure it to open via notepad.Also you should check the exception that it throws,
If File association is missing then it will launch the Openwith dialog.
If it is associated with wrong program then you can change it manually.
If you want to find association type pragmatically then, I would suggest looking at this answer.
How to I get file type information....

You're saying your code is working fine in other OS and other file formats even in Win 7.
Let's try following checks to verify if things are correct
Verify if notepad.exe is in path
Start -> Run -> notepad.exe should launch Notepad
Double click on a .txt file and see if it automatically opens in Notepad
Verify if Process.Start("notepad.exe") starts an instance of Notepad
var process = Process.Start(file used in step 2); and verify the returned process info in the debug mode and see if says the newly created process is still running or not.

I've had this happen on Windows 7 before. It's likely that your Path environment variable has become corrupted. The maximum number of characters that can be used in the Path variable is 2047. Installing many executables on your machine can overflow the Path variable. Here is a SO discussion that shows some ideas to get around it:
How do you avoid over-populating the PATH Environment Variable in Windows?
If you just need to get notepad running again quickly, you can modify the Path environment variable and just put the system location to Notepad at the beginning of the variable. (ex. "c:\windows\system32\notepad.exe").
And if you're not sure how to modify your Path variable, here is a good how-to:
http://geekswithblogs.net/renso/archive/2009/10/21/how-to-set-the-windows-path-in-windows-7.aspx

What about just using
Process.start("start", "d:\\test.txt")
or
Process.start("explorer", "d:\\test.txt")
or
Process.start("cmd", "/c notepad.exe d:\\test.txt")
If it still doesn't work, try using the straight shellexecute, as described here
Executing another program from C#, do I need to parse the "command line" from registry myself?
https://www.gamedev.net/topic/310631-shellexecuteex-api-call-in-c/

Related

How to open a file's folder? C# [duplicate]

I saw the other topic and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong?
System.Diagnostics.Process.Start("explorer.exe", #"c:\teste");
Have you made sure that the folder "c:\teste" exists? If it doesn't, explorer will open showing some default folder (in my case "C:\Users\[user name]\Documents").
Update
I have tried the following variations:
// opens the folder in explorer
Process.Start(#"c:\temp");
// opens the folder in explorer
Process.Start("explorer.exe", #"c:\temp");
// throws exception
Process.Start(#"c:\does_not_exist");
// opens explorer, showing some other folder)
Process.Start("explorer.exe", #"c:\does_not_exist");
If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following:
Open the Run dialog, enter "explorer.exe" and hit enter
Open a command prompt, type "explorer.exe" and hit enter
Just for completeness, if all you want to do is to open a folder, use this:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() {
FileName = "C:\\teste\\",
UseShellExecute = true,
Verb = "open"
});
Ensure FileName ends with Path.DirectorySeparatorChar to make it unambiguously point to a folder. (Thanks to #binki.)
This solution won't work for opening a folder and selecting an item, since there doesn't seem a verb for that.
If you want to select the file or folder you can use the following:
Process.Start("explorer.exe", "/select, c:\\teste");
You're using the # symbol, which removes the need for escaping your backslashes.
Remove the # or replace \\ with \
You don't need the double backslash when using unescaped strings:
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
You should use one of the System.Diagnostics.Process.Start() overloads. It's quite simple!
If you don't place the filename of the process you want to run (explorer.exe), the system will recognize it as a valid folder path and try to attach it to the already running Explorer process. In this case, if the folder is already open, Explorer will do nothing.
If you place the filename of the process (as you did), the system will try to run a new instance of the process, passing the second string as a parameter. If the string is a valid folder, it is opened on the newly created process, if not, the new process will do nothing.
I don't know how invalid folder paths are treated by the process in any case. Using System.IO.Directory.Exists() should be enough to ensure that.
Use an overloaded version of the method that takes a ProcessStartInfo instance and set the ProcessWindowStyle property to a value that works for you.
You're escaping the backslash when the at sign does that for you.
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
This code works fine from the VS2010 environment and opens the local folder properly, but if you host the same application in IIS and try to open then it will fail for sure.
Ive just had this issue, and i found out why. my reason isnt listed here so anyone else who gets this issue and none of these fix it.
If you run Visual Studio as another user and attempt to use Process.Start it will run in that users context and you will not see it on your screen.
Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?
The following code should open a new explorer instance
class sample{
static void Main()
{
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
}
}
Do you have a lot of applications running when you are trying this?
I encounter weird behavior at work sometimes because my system runs out of GDI Handles as I have so many windows open (our apps use alot).
When this happens, windows and context menus no long appear until I close something to free up some GDI handles.
The default limit in XP and Vista is 10000.
It is not uncommon for my DevStudio to have 1500 GDI handles, so if you have a couple of copies of Dev studio open, it can eat them up pretty quickly. You can add a column in TaskManager to see how many handles are being used by each process.
There is a registry tweak you can do to increase the limit.
For more information see http://msdn.microsoft.com/en-us/library/ms724291(VS.85).aspx
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
Just change the path or declare it in a string

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 would I find an exe's path just by knowing its name?

How Would I find another exe's path by knowing its name in .net?
Would I add name to the OS environment variable?
Would the other application have to 'register' itself somewhere else?
I need App A to start-up App B and call some WCF services on it.
Thanks!
To answer your question: you cannot know the path simply by knowing the name. An exe can reside anywhere on the file system. There can be multiple instances of it that don't know about each other. Multiple exe files that are completely different can have the same name.
You could take one of several approaches to get round this, depending on the exe you are targetting:
get the user to browse for the exe using a normal file browse dialog
search the file system
see what traces the target exe leaves on the system (filesystem, registry, environmental variables, etc) and use those traces to locate the exe
For either of these options you save the result so you don't have to execute it again when your app is run the next time.
Searching the filesystem could take some time, you are not guaranteed to find the exe (depending upon the user level your app is running as) and you may get false positives, especially if the app is called something dumb like setup.exe.
Getting the user to locate the exe the first time you run is possibly the most reliable way of locating it, but then you have to decide what to do if your app runs but the target exe is no longer at the specified location, or the user has chosen the wrong exe.
If you have some control over App B (i.e. it is your product), then you could consider adding some info to a known spot in the registry when App B gets installed, so that App A can locate it easily. You still need to have a plan B though in case the info is missing.
Reference a path to a shortcut of the exe in the config setting, that way if the exe ever moves around the shortcut will still be up-to-date. Try it, make a shortcut to a exe, then cut and paste the exe somewhere else, then double click the shortcut and you'll see it points to the exe's new location thus will not require changes to app A if the location app B changes.
Really, just make the App B a windows service and start it up when needed.
UPDATE:
Another suggestion would be to create a hard link to the AppB's EXE:
mklink /H AppB-link.exe path_to_actual_exe
Or a symbolic link to whole directory where App B resides:
mklink /D virtual_directory path_to_actual_directory

c# program works from cmd prompt but not run separately?

I would post a snippet, but I honestly have no idea what part of my code could possibly be doing this. The program is sizable, I don't want to make you all wade through it. What kinds of things could possibly be the cause of this? Everything works perfectly when called from the command prompt: "readoo.exe". But when I click the exe in its file. . . "readoo.exe has encountered a problem and needs to close. . ."
this is intended to eventually be a scheduled task -> i'm worried, will it work?
i've never debugged, all i've ever used is notepad. I am learning, and feel that this strengthens my understanding of a project.
it crashes nearly immediately. there are no shortcuts, though the file paths are relative.
trying this method: shortcut -> properties -> shortcut -> Start In. I don't have a "shortcut" option
my program reads log files, parses, and creates 4 new files based on the found content
Microsoft Error Report says file not found. But how can this be? the files are there, albeit relative.
Take a copy of your project, and then start hacking bits out of it. When it no longer crashes, you've removed the bit causing the problem.
At what point does it fail when you double-click on it? Immediately, or only when you take a certain action?
You could also add a lot of logging to it, which could indicate where the problem is too.
This is probably looking for a dll that it can't find or is finding a different version from what it wants.
You could try Process Monitor or Process Explorer from sysinternals to see what dlls it loads when it does work and where it finds them.
Try putting a System.Diagnostics.Debugger.Break()call as the first thing in Main() and you'll be asked to attach a debugger - this should definitely show you what is different betweent the 2 invocations.
I would start with identifying what is different in the two methods of execution. Is there a shortcut modifying anything?
The starting directory?
The execution account?
command line arguments?
There are 2 things that it could be:
The current directory could be different when you click on the program or run from the command prompt.
The settings and path could be different when you click on the programe you are using the standard command prompt, are you opening the visual studio command prompt when you run the program from the prompt.
If your application relies on some file that should be on the same path of that exe, that can occurr.
You will have to change the properties of the exe (or shortcut to the exe) to "Start In" the directory where your exe is. For a shortcut, right click on the shortcut -> properties -> shortcut -> Start In.
I guess that is what I think could be the cause.
EDIT: Add a Console.ReadLine towards the end of your code to make it pause for you to see any exception thrown. That should help when you run it using windows explorer.
Put a try/catch around your code and output the exception message to the console in the catch block. That should give you some clues.

Open a folder using Process.Start

I saw the other topic and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong?
System.Diagnostics.Process.Start("explorer.exe", #"c:\teste");
Have you made sure that the folder "c:\teste" exists? If it doesn't, explorer will open showing some default folder (in my case "C:\Users\[user name]\Documents").
Update
I have tried the following variations:
// opens the folder in explorer
Process.Start(#"c:\temp");
// opens the folder in explorer
Process.Start("explorer.exe", #"c:\temp");
// throws exception
Process.Start(#"c:\does_not_exist");
// opens explorer, showing some other folder)
Process.Start("explorer.exe", #"c:\does_not_exist");
If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following:
Open the Run dialog, enter "explorer.exe" and hit enter
Open a command prompt, type "explorer.exe" and hit enter
Just for completeness, if all you want to do is to open a folder, use this:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() {
FileName = "C:\\teste\\",
UseShellExecute = true,
Verb = "open"
});
Ensure FileName ends with Path.DirectorySeparatorChar to make it unambiguously point to a folder. (Thanks to #binki.)
This solution won't work for opening a folder and selecting an item, since there doesn't seem a verb for that.
If you want to select the file or folder you can use the following:
Process.Start("explorer.exe", "/select, c:\\teste");
You're using the # symbol, which removes the need for escaping your backslashes.
Remove the # or replace \\ with \
You don't need the double backslash when using unescaped strings:
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
You should use one of the System.Diagnostics.Process.Start() overloads. It's quite simple!
If you don't place the filename of the process you want to run (explorer.exe), the system will recognize it as a valid folder path and try to attach it to the already running Explorer process. In this case, if the folder is already open, Explorer will do nothing.
If you place the filename of the process (as you did), the system will try to run a new instance of the process, passing the second string as a parameter. If the string is a valid folder, it is opened on the newly created process, if not, the new process will do nothing.
I don't know how invalid folder paths are treated by the process in any case. Using System.IO.Directory.Exists() should be enough to ensure that.
Use an overloaded version of the method that takes a ProcessStartInfo instance and set the ProcessWindowStyle property to a value that works for you.
You're escaping the backslash when the at sign does that for you.
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
This code works fine from the VS2010 environment and opens the local folder properly, but if you host the same application in IIS and try to open then it will fail for sure.
Ive just had this issue, and i found out why. my reason isnt listed here so anyone else who gets this issue and none of these fix it.
If you run Visual Studio as another user and attempt to use Process.Start it will run in that users context and you will not see it on your screen.
Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?
The following code should open a new explorer instance
class sample{
static void Main()
{
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
}
}
Do you have a lot of applications running when you are trying this?
I encounter weird behavior at work sometimes because my system runs out of GDI Handles as I have so many windows open (our apps use alot).
When this happens, windows and context menus no long appear until I close something to free up some GDI handles.
The default limit in XP and Vista is 10000.
It is not uncommon for my DevStudio to have 1500 GDI handles, so if you have a couple of copies of Dev studio open, it can eat them up pretty quickly. You can add a column in TaskManager to see how many handles are being used by each process.
There is a registry tweak you can do to increase the limit.
For more information see http://msdn.microsoft.com/en-us/library/ms724291(VS.85).aspx
System.Diagnostics.Process.Start("explorer.exe",#"c:\teste");
Just change the path or declare it in a string

Categories