GetDirectoryName
Path.GetDirectoryName方法接受一个文件路径作为参数,返回该文件路径的目录部分,即去掉文件名后的路径。例如:
string filePath = @"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe";
string directoryPath = Path.GetDirectoryName(filePath);
Console.WriteLine(directoryPath); // 输出:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
Location
Assembly.Location属性获取当前执行的程序集的完整路径。例如:
using System.Reflection;
string assemblyPath = Assembly.GetExecutingAssembly().Location;
Console.WriteLine(assemblyPath); // 输出:C:\Users\user\source\repos\MyProject\bin\Debug\MyProject.exe
这里使用Assembly.GetExecutingAssembly()方法获取当前执行的程序集,然后调用Location属性获取完整路径。通常情况下,Assembly.Location属性和Path.GetDirectoryName方法可以用于读取配置文件或资源文件等需要在程序集同一目录下的文件。
public class GPath
{
public static string AssemblyRunRootPath = Path.GetDirectoryName(typeof(GPath).Assembly.Location);
}
这段代码定义了一个名为GPath的静态类,其中包含一个名为AssemblyRunRootPath的静态属性。这个属性的值是通过调用Path.GetDirectoryName和typeof(GPath).Assembly.Location来获取的。
Path.GetDirectoryName是一个静态方法,它返回指定路径字符串的目录信息,该路径字符串包含一个文件名或目录名。在这个例子中,typeof(GPath).Assembly.Location返回的是GPath类所在的程序集的路径。然后,Path.GetDirectoryName方法被调用以获取这个路径的目录信息,也就是程序集所在的根目录路径。
这个静态属性可以在整个应用程序中访问,用于获取应用程序运行时所在的根目录路径。