如何获取当前工作目录路径c#?

我在项目中有一个光标文件。 我在代码中给出了绝对路径,即

F:/r.cur 

问题是这是硬编码的路径我希望相对路径,以便如果我将我的解决方案移动到另一个系统代码不应该影响。

请建议如何设置相对路径

 //current code i am using p.Cursor = new Cursor("F:/r.cur"); 

您可以使用静态Directory类 – 但是当前目录与原始目录不同,原始目录是启动进程的目录。

 System.IO.Directory.GetCurrentDirectory(); 

因此,您可以使用以下命令获取应用程序可执行文件的目录路径:

 System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); 

使用Application.StartupPath返回启动应用程序的可执行文件的路径。

  string pathCur = Path.Combine(Application.StartupPath, @"..\..\r.cur"); Cursor = new Cursor(pathCur); 

你也可以过关
System.IO.Directory.GetCurrentDirectory();
但它也显示了bin和debug文件夹,如果您不想要这些文件夹,那么您可以使用该代码:

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

输出:

GetFileName:Mouse.aspx
GetFileNameWithoutExtension:鼠标
GetDirectoryName:E:\ abccom \ Cat

快乐编码:)

您可以使用System.IO.Directory.GetCurrentDirectory()获取当前工作目录。 它将返回您当前的可执行文件路径。

谢谢

Application.StartupPath应该为您提供运行应用程序的应用程序路径。 我会在应用程序文件夹下创建一个目录结构。 例如,如果“C:\ Program Files \ MyApp”是我的应用程序文件夹,那么我将在其下创建一个名为cursors的文件夹(C:\ Program Files \ MyApp \ Cursors“)并将所有游标放在此文件夹中。