How to get current working directory path c#?
Solution 1
You can use static Directory
class - however current directory is distinct from the original directory, which is the one from which the process was started.
System.IO.Directory.GetCurrentDirectory();
So you can use the following to get the directory path of the application executable:
System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
Solution 2
use Application.StartupPath returns path for the executable file that started the application.
string pathCur = Path.Combine(Application.StartupPath, @"..\..\r.cur");
Cursor = new Cursor(pathCur);
Solution 3
You can also get by
System.IO.Directory.GetCurrentDirectory();
but it shows bin and debug folder also, if you don't want these folder so you can use that code :
string page = "E:\abccom\Cat\Mouse.aspx"
string name = Path.GetFileName(page );
string nameKey = Path.GetFileNameWithoutExtension(page );
string directory = Path.GetDirectoryName(page );
Console.WriteLine("{0}, {1}, {2}, {3}",
page, name, nameKey, directory);
Output:
GetFileName: Mouse.aspx
GetFileNameWithoutExtension: Mouse
GetDirectoryName: E:\abccom\Cat
Happy Coding :)
Solution 4
Super late to this party, but this works for me when I'm in unit tests.
var currentDirectory = Directory.GetCurrentDirectory();
If you need the root of the project, and not the bin directory then this:
var currentDirectory = Directory.GetCurrentDirectory();
var basePath = currentDirectory.Split(new string[] { "\\bin" }, StringSplitOptions.None)[0];
It'll be different if you're on a website.
yogeshkmrsoni01
Updated on September 28, 2021Comments
-
yogeshkmrsoni01 over 2 years
I have a cursor file in project. I have given the absolute path in code i.e
F:/r.cur
the problem is this is hard-coded path And i Want relative path so that if i move my solution to another system the code should not effect.
please suggest how to set relative path
//current code i am using p.Cursor = new Cursor("F:/r.cur");
-
yogeshkmrsoni01 over 10 yearsIts returning the C:\Users\yogeshkmrsoni\Documents\Visual Studio 2010\Projects\ProjectName\bin\Release ; but i want to copy cursor file to C:\Users\yogeshkmrsoni\Documents\Visual Studio 2010\Projects\ProjectName\r.cur, can u suggest any other way
-
Avinash Jain about 8 yearsThe above code dosen't work in WPF as as it not have System.Windows.Forms namespace. Use the following instead System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
-
sonyisda1 over 5 yearsjust to note: this is only for WinForms