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

问题描述 投票:42回答:7

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

F:/r.cur  

问题是这是硬编码的路径,并且我想要相对路径,这样,如果我将解决方案移至另一个系统,则代码不会生效。

请建议如何设置相对路径

//current code i am using 
 p.Cursor = new Cursor("F:/r.cur");
c# .net visual-studio-2010 c#-4.0
7个回答
53
投票
您可以使用静态Directory类-但是当前目录与原始目录不同,原始目录是从该目录开始的过程。

System.IO.Directory.GetCurrentDirectory();

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

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


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

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


3
投票
您也可以通过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.aspxGetFileNameWithoutExtension:鼠标GetDirectoryName:的目录:E:\ abccom \ Cat

快乐编码:)


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

谢谢


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

0
投票
[System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)在启动时将为您提供完整的路径。

此后,如果您*

确实想找到开发中(作为您在其他答案中的评论) *,请首先使用FileInfo(thestringwithfilenamepath).Directory.Name查找路径。


0
投票
参加这个聚会的时间太晚了,但这在我进行单元测试时对我有用。

var currentDirectory = Directory.GetCurrentDirectory();

如果您需要项目的根目录,而不是bin目录,那么此:

var currentDirectory = Directory.GetCurrentDirectory(); var basePath = currentDirectory.Split(new string[] { "\\bin" }, StringSplitOptions.None)[0];

如果您在网站上,情况会有所不同。
© www.soinside.com 2019 - 2024. All rights reserved.