C# 获取当前文件夹路径
在 C# 中,我们可以使用 Directory
类来处理目录问题。目录或文件夹用于存储文件。
在本文中,我们将讨论用于获取当前文件夹路径的各种方法。
C# 使用 GetCurrentDirectory()
方法获取当前文件夹路径
方法 GetCurrentDirectory()
用于获取存储你正在运行的应用程序的当前文件夹路径。在这种情况下,它将从程序运行目录中获取目录。
使用此方法的正确语法如下:
Directory.GetCurrentDirectory();
示例代码:
using System;
using System.IO;
namespace CurrentFolder
{
class Folder
{
static void Main(string[] args)
{
var CurrentDirectory = Directory.GetCurrentDirectory();
Console.WriteLine(CurrentDirectory);
}
}
}
输出:
C:\Users\Cv\source\repos\ClassLibrary1\ClassLibrary1\bin\Debug\netstandard2.0
//Directory where the program is saved i.e current folder path
C# 使用 GetDirectoryName()
方法获取当前文件夹路径
方法 GetDirectoryName()
用于获取当前目录。它接受一个字符串作为参数来说明文件的路径。
但是如果我们不知道文件的路径,那么我们将 Assembly.GetEntryAssembly().Location
作为此方法的参数传递。Assembly.GetEntryAssembly().Location
获取带有文件名的文件路径。使用 GetDirectoryName()
获取当前目录。
使用此方法的正确语法如下:
GetDirectoryName(PathString);
System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
示例代码:
using System;
using System.Reflection;
namespace CurrentFolder
{
class Folder
{
static void Main(string[] args)
{
var CurrentDirectory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Console.WriteLine(CurrentDirectory);
}
}
}
输出:
C:\Users\Cv\source\repos\ClassLibrary1\ClassLibrary1\bin\Debug\netstandard2.0
//Directory where the program is saved i.e current folder path
C# 使用 CurrentDirectory
属性获取当前文件夹路径
CurrentDirectory
用于获取当前工作目录的完整路径。CurrentDirectory
是在 System.Environment
类中定义的,这就是为什么将其用作 Environment.CurrentDirectory
的原因。
使用此方法的正确语法如下:
var CurrentDirectory = Environment.CurrentDirectory;
示例代码:
using System;
namespace CurrentFolder
{
class Folder
{
static void Main()
{
var CurrentDirectory = Environment.CurrentDirectory;
Console.WriteLine(CurrentDirectory);
}
}
}
输出:
C:\Users\Cv\source\repos\ClassLibrary1\ClassLibrary1\bin\Debug\netstandard2.0
//Directory where the program is saved i.e current folder path
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。