I wrote a program need to call an external exe using
Process proc = Process.Start(filepath).
I specify the absolute path of the exe and it works fine. However, I need to use this program in different computers. Each time the exe has a different absolute path and I need to change the code for this part. I would like to know is there a way that I don't need to change the code? Thanks in advance!
You are asking the wrong question. Is not how to modify the API to work with your fixed requirements ("launch process w/o knowing the path", ignoring for a moment what huge security problem that is). The question you should ask is How can I modify my code to match the API I use?
Since starting a process works better if a full path is given (it also works if the executable name is in %PATH%, but that is a different topic), have you app figure out the correct path and then launch the process. There are countless ways to achieve this. Probably the safest option is to use an App.Setting that points to the path. At deployment the app is properly configured with the location of the required program. there are (many) more ways to do this, it will all depend on what you're actually trying to solve, more details would be needed.
If both exe-files are in the same folder, then
winforms:
var filepath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), otherexename);
Process.Start(filepath);
wpf:
var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, otherexename)
Process.Start(filepath);
In a windows service, you can do the following to get the directory of the currently running assembly, then to generate the right path to your exe:
var directory = Path.GetDirectoryName(
new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
var exeLocation = Path.Combine(directory,"myExe.exe");
Related
A basic question:
I have a C# Windows application which runs fine when executed from its own directory, by typing
program1.exe
but when I execute it from another directory giving full path like
d:/progs/myprog/program1.exe
it crashes. And I really need to do it this way :)
I suppose it is connected to reading some files by the program which are in the same directory. My suspected line is:
using (XmlReader OdczytywaczXML = XmlReader.Create(#"config.xml"))
Can it be the problem? I wouldn't like to give full paths to files as I'd like my program to work anywhere just by copying the files.
Oh, and I have no idea how to simulate such condition (running from another directory) while debugging - is it possible?
You should detect your program location and construct full path to config.xml in this case, for example:
var filePath = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
#"config.xml");
To simulate condition, go to project properties, page "Debug" and set Working Directory.
This is surely the problem. You can add directory information on that line. In WinForms you can use Application.StartupPath for example.
In General you can use System.Reflection.Assembly.GetExecutingAssembly().Location
The issue is that the Working Directory isn't the same when you just execute it from the command-line. You'll want to safeguard this:
var path = Path.Combine(Assembly.GetExecutingAssembly().Location, "config.xml");
using (XmlReader OdczytywaczXML = XmlReader.Create(path))
The Location property will do the following for you:
Gets the full path or UNC location of the loaded file that contains the manifest.
One thing to note here is that if you added a shortcut to the Desktop and set the Working Directory, before changing the code, you would find the application runs fine. Do that first to verify the fix worked.
I have an XML file I'm streaming as an XDocument. I need to be able to get the full path of the file (NOT the bin/Debug path) using reflection or the like (so this will be the path from the User's machine it lives on).
I have tried about a zillion different ways, including:
System.Reflection.Assembly.GetCallingAssembly().Location
System.Reflectin.Assembly.GetEntryAssembly().Location
System.Reflection.GetExecutingAssembly().Location
AppDomain.CurrentDomain.BaseDirectory.
How do I look use System.IO to find the path on the User's machine to my file?? Quite suprised I haven't found the simple answer after googling all day.
::EDIT:: I've now found out that there is no way to "reflectively" locate a path dynamically based on whether the application is running in the debugger or not. My only option is to do some detection.
Thanks in advance!!
I'm assuming that the file is in a child directory of the executable?
You can get the full path of the current working directory (ie where your .exe was run from) by using the Environment class. You can then concatanate this with the child directory
Environment.CurrentDirectory + #"\folder\file.xml"
http://msdn.microsoft.com/en-us/library/system.environment.aspx
Hope this helps!
EDIT: After reading up a little it turns out that CurrentDirectory can be changed rather easily. The accepted answer here Environment.CurrentDirectory is yielding unexpected results when running installed app offers a more reliable method.
Found my answer here (using path stripping and GetFullPath() ). It's a real bummer there's no way around just stripping the bin/debug part of the path. I used the third part of the question linked above.
I am new to C# and I have made a simple Windows Forms Application that basically updates the persons files for a game.
They have to manually move and delete certain folders just to change version every time. I have successfully accomplished this.
However before I start giving it out I really should improve it. I know I need to change the name of the processes and remove my descriptions ETC.
I have stumbled onto an error and instead of me taking a guess I think it is best to get an opinion from a more experienced person about how to do this.
I am going to use Inno Setup to make the installer for my application, this way I can be sure it will go into their program files 32 and 64 bit. So I know this will be in program files.
So now I am wondering if I have done this the correct way or not? I was using this format to find their program files:
string programFilesFolder = Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
However, would this work on all windows systems(XP, Vista, Win7, Win8) and is it completely accurate? I was going to use the above, and then use this:
string PATCHSELECTOR = Path.Combine(programFiles, #"PATCH SELECTOR");
if (Directory.Exists(PATCHSELECTOR))
{
string GamereliteFolder = Path.Combine(programFiles, #"GAMERELITE~1");
if (Directory.Exists(GamereliteFolder))
And then I move the files using the string method. If the file exists it is deleted before I copy the file over from PATCH SELECTOR to GAMERELITE.
Also will windows XP support using the .exe with an assembly resource embedded which is making the program need to be ran as administrator? I previously was making the assembly work through UAC however that wouldnt always work if they have UAC off or if it is XP so I thought I would try the admin assembly instead.
Can anyone possibly give me some insight, ideas or links?
For executables (not sure for websites & web application) this returns the directory where the executable lives (it's actually the base path where the framework will probe for Assemblies to load, 99% of the the that's the same thing).
System.AppDomain.CurrentDomain.BaseDirectory
This method works for any executable located in a folder which is defined in the windows PATH variable:
private string LocateEXE(String fileName)
{
string path = Environment.GetEnvironmentVariable("path");
string[] folders = path.Split(';');
foreach (var folder in folders)
{
if (File.Exists(Path.Combine(folder, fileName)))
{
return Path.Combine(folder, fileName);
}
}
return String.Empty;
}
Usage:
string pathToEXE = LocateEXE("Example.exe");
Reference:
how to find the execution path of a installed software
How can I get another application's installation path programmatically?
Couple things:
Among the already stated answers, Assembly.GetExecutingAssembly().Location will also give you the full file path of the currently "executing" Assembly. (Alternatively, GetCurrentAssembly)
If I'm reading your question correctly, you're trying to find both your own location as well as another application's. I would highly recommend seeing if the other application has a registry key that specifies the exact location - it'll make your copy step WAY more stable.
How do I debug my C# app when it really needs to be running from a specific folder and not from bin/debug? One of the first things my program does for example is determine what set of tools will be presented based on the executable file it finds. But since its running from the debug folder it can't find them. I can add the file there but that seems silly. There has to be a better way. Plus, there's really a bunch of other thighs it does that really requires it to be running from the proper folder eg. Z:\test.
I thought it might be the "Working Directory" setting under the "Debug" tab in Properties but that didn't seem to do anything. I'm using VS2010 and C# btw...
I hope I'm making sense.
Thanks
You can specify another output folder for your build.
Try setting Environment.CurrentDirectory to the directory you want to simulate.
Environment.CurrentDirectory = #"C:\SimulateThisDirectory\";
You can use
System.IO.Directory.SetCurrentDirectory("your-path");
from your code.
You need to differ between two things:
path from which process is started
current working directory of the process
First one you can't simulate easily. It would probably involve creating a symbolic link or creating some sort of rootkit.
As for second one, your method is fine, and you can check working directory in runtime by using Directory.GetCurrentDirectory or set it using Directory.SetCurrentDirectory.
Take note that if you are looking up directory of executing assembly, you will get path from which process is started.
You can run your program from as normal from the specific directory and then just attach the debugger
http://msdn.microsoft.com/en-us/library/c6wf8e4z.aspx
so, i am building a new WinForms with update my program.
the thing is, i am not installing any-thing. so,when i give my freinds my program, that can put it where ever they want. how can i know where did they put it?
like, lets say my program called "MyProg".
so lets say my freind puted "MyProg" in C:\programs\install\SayHello.
and i want my program to know where she is and save it to xml(everytimes she loads).
so, i know how to use everything here, i just need to know how can i get the folder path i am in now. (for my explined the foldepath = "C:\programs\install\SayHello.")
Anyone?
Thanks again,
Alon. :)
From How do I get the name of the current executable in C#?, to find the name of the currently running assembly:
string file = object_of_type_in_application_assembly.GetType().Assembly.Location;
string app = System.IO.Path.GetFileNameWithoutExtension(file);
so to find the path of the currently running assembly
string file = object_of_type_in_application_assembly.GetType().Assembly.Location;
string path = System.IO.Path.GetDirectoryName(file);
should do the job.
Environment.CurrentDirectory won't necessarily return what you want, as it's possible to run the program from a different folder at the console.
There are a few options, including:
Application.ExecutablePath
Search for "get exe location c#" for more variations on this.
Environment.CurrentDirectory contains the current directory.
Application.StartupPath
should do the same in your case.