[英]How to get current working directory path c#?
我在项目中有一个 cursor 文件。 我已经在代码中给出了绝对路径,即
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);
输出:
获取文件名:Mouse.aspx
GetFileNameWithoutExtension: 鼠标
获取目录名称:E:\\abccom\\Cat
快乐编码:)
怎么样: Environment.CurrentDirectory
查看更多信息: https://learn.microsoft.com/en-us/do.net/api/system.environment?view.net-5.0
参加这个聚会太晚了,但是当我进行单元测试时,这对我有用。
var currentDirectory = Directory.GetCurrentDirectory();
如果您需要项目的根目录,而不是 bin 目录,则:
var currentDirectory = Directory.GetCurrentDirectory();
var basePath = currentDirectory.Split(new string[] { "\\bin" }, StringSplitOptions.None)[0];
如果您在网站上,情况会有所不同。
您可以使用System.IO.Directory.GetCurrentDirectory()
获取当前工作目录。 它将返回您当前的可执行路径。
谢谢
Application.StartupPath 应该为您提供应用程序运行所在的应用程序路径。 我会在应用程序文件夹下创建一个目录结构。 例如,如果“C:\\
System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
在启动时会给你完整的路径。
之后,如果您 *真的想在开发过程中找到一些东西(正如您在其他答案中的评论所指出的那样) *,首先使用FileInfo(thestringwithfilenamepath).Directory.Name
找到路径。
派对超级超级晚。
但是取决于你的意思 - 如果你在你的应用程序代码最终部署到的目录之后(例如在你的测试机器上),那么这适用于常规控制台应用程序:
//gives something like D:\source\repos\Repo\src\AppName\bin\Debug\net6.0\Appame.dll
var assemblyLocation = Assembly.GetEntryAssembly().Location;
//gives something like D:\source\repos\Repo\src\AppName\bin\Debug\net6.0
var currentDirectory = Path.GetDirectoryName(assemblyLocation);
//gives something like D:\source\repos\Repo\src\AppName
var appRootFolder = currentDirectory.Split("\\bin")[0];
Console.WriteLine($"The root of the application is here: {appRootFolder}");
对于 .net 6 和 .net 7 我使用:
var filePath = Path.Combine(AppContext.BaseDirectory, $"someFile.txt");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.