The code, in both case is identical:
This is working and opening the text file in notepad
editor = "notepad.exe";
if (File.Exists(briefingFile))
{
Process.Start(editor, briefingFile);
}
This one does is not work:
editor = "notepad .exe";
if (File.Exists(briefingFile))
{
Process.Start(editor, briefingFile);
}
It is the same test file and I have notepad installed. I Also tried to specify notepad with full path but the result is the same. Instead of opening notepad I get the attached error messages which tries to create new file or open missing files.
CodePudding user response:
The notepad.exe
file is part of Windows and lives in the Windows folder, which is part of the default search path (an environment variable). Notepad .exe
is not part of Windows, and so its home folder is not part of the default search path.
Therefore, to open a process using Notepad you must also know the full path to the program.
When trying the full path, make sure you escape the folder separator characters properly, and you must make sure to account for spaces in your path. In this case, the reason you see the C:\Program
error is because you haven't yet accounted for the space in Program Files
.
editor = @"""C:\Program Files\Notepad \notepad .exe""";
try
{
Process.Start(editor, briefingFile);
}
catch(Exception ex)
{
// Do something here
}
Also note how I switched to an exception handler instead of File.Exists()
. Disk I/O is one of those rare places where you should prefer handling the exception. File.Exists()
is particularly bad for this, and should be avoided.
One other option here is if you have enough control for your target machines to know for sure Notepad is even installed, then you also have enough control register it as the default program for the files types your using, meaning you can skip selecting a program name at all:
Process.Start(briefingFile);
CodePudding user response:
There is nothing wrong with your code, although, as Joel stated, there are drawbacks to using File.Exists()
. You should only need to make sure that the Notepad folder is in your User/System Environment PATH variables. I added the path for my Notepad folder on this PC, which is just C:\Program Files\Notepad \
, and ran the same code and it opens the file in Notepad just fine.