Get Correct folder using c# - c#

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.

Related

call exe using Process without absolute path

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");

Visual Studio 2012 - access file in different directory

I know there are many topics similar to this, but I've been unable to find a solution after looking through dozens of results.
I have a Project "Foo", and my controller is at "Foo\Controllers\Bar.cs, and in that C# file, I want to read from a file, located at "Foo\Data\Stuff.txt". It's so simple, but nothing I've tried works, mainly because things like Directory.GetCurrentDirectory() and all similar built-in functions reference the executing directory (in my case, "C:\Program Files (x86)\IIS Express").
What am I doing wrong? Or if I missed an identical question, please direct me there, this seems to small an issue to have spent so much time on. Thanks!
With command Server.MapPath("Foo\Data\Stuff.txt") you will find the phisical path where the file is stored
It sounds like you might be looking for System.Reflection.Assembly.GetExecutingAssembly().CodeBase, which allows you to find exactly where your running .exe is located; regardless of whether you're in the debugger or not.
Here's an example that uses "CodeBase" to find the path, then reads the Windows version info from the .exe:
// GetWindowsVersion: Fetch Winver info from specified file
public static string GetWindowsFileVersion()
{
String codeBaseUri =
System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
String codeBase =
new Uri(codeBaseUri).LocalPath;
System.Diagnostics.FileVersionInfo info = FileVersionInfo.GetVersionInfo(codeBase);
return info.FileVersion.ToString();
}

Finding Install path of a program

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.

full path of a folder in c#

i need to get the full folder path in a windows project using c#.I tried with path.getFulPath(filename).bt it returns the application path+filename.how can i get the actual path like "D:\eclipse_files\ads_data"?
A relative path such as myfile.txt is always resolved in relation to the current working directory.
In your case the current working directory seems to be D:\eclipse_files\ads_data so your relative file path gets resolved to D:\eclipse_files\ads_data\myfile.txt when you call Path.GetFullPath.
To solve the problem, either make sure that you start with an absolute path from the beginning, or, that your working directory is set correctly.
You can get/set the working directory using the Directory.GetCurrentDirectory and Directory.SetCurrentDirectory methods.
Your question is not very clear, but I think you're looking for this:
string path = Path.GetDirectoryName(filename);
If I have understood correctly, you have a filename, for example 'doc.txt', and you want to have a method to return the full path of this file regardless of where the application runs from?
If this is what you ask it is not possible. Have you considered that there might be several files called 'doc.txt' on your harddrives?
The best you can hope to do it to search all harddrives, and return a list of all files found with the same name, but that will just be ridicously slow.

Getting the absolute path of the executable, using C#?

Have a look at this pseudocode:
string exe_path = system.get_exe_path()
print "This executable is located in " + exe_path
If I build the above program and place the executable in C:/meow/, It would print out This executable is located in C:/meow/ each time it is run, regardless of the current working directory.
How could I easily accomplish this using C#?
MSDN has an article that says to use System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase; if you need the directory, use System.IO.Path.GetDirectoryName on that result.
Or, there's the shorter Application.ExecutablePath which "Gets the path for the executable file that started the application, including the executable name" so that might mean it's slightly less reliable depending on how the application was launched.
AppDomain.CurrentDomain.BaseDirectory
using System.Reflection;
string myExeDir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.ToString();
var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.
For that reason I am posting the answer listed in the comments to give it the exposure it deserves.
"Gets the path or UNC location of the loaded file that contains the manifest."
See: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx
Application.ResourceAssembly.Location
Suppose i have .config file in console app and now am getting like below.
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\YourFolderName\\log4net.config";
On my side, I used, with a form application:
String Directory = System.Windows.Forms.Application.StartupPath;
it takes the application startup path.
The one that worked for me and isn't above was Process.GetCurrentProcess().MainModule.FileName.
If you are planning to build a console application to be used with Task Scheduler, I'd recommend using this approach:
var execDirectoryPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)?.Replace("file:\\", "");
This way, the path will adapt to whatever location you place your executable file in.

Categories