WPF-模拟动态更换logo的过程(1),如何获取程序的根目录。

假设现在需要从网上下载一个图片到项目目录下,展示下载的图片,然后删除正在展示的图片(模拟更换logo的过程),替换新的图片。  

下载图片之前需要确定图片应存的地址,图片不能存在本地(比如图片存在D盘的某个文件下,但是用户如果没有D盘就会出错),所以应该存在程序的根目录下。

有俩个方法可以获取程序的根目录。

1.这种方法比较灵活,可以获取根目录以及其之上的目录。

public string GetProjectRootPath()
{
string rootPath = "";
string BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; // F:WAF ProjectsmjlcodeHomeDecorationPSDHomeDecorationPSDinDebug
// 向上回退三级,才能到项目的根目录
rootPath = BaseDirectoryPath.Substring(0, BaseDirectoryPath.LastIndexOf("\")); // 第一个是转义符,所以要写两个
rootPath = rootPath.Substring(0, rootPath.LastIndexOf("\"));
rootPath = rootPath.Substring(0, rootPath.LastIndexOf("\")); // F:WAF ProjectsmjlcodeHomeDecorationPSDHomeDecorationPSD
return rootPath;
}

2.第二种方法简洁方便(另外把图片存在bin文件与.exe在同一目录下会有优点。后面会提到。)

$"{System.Environment.CurrentDirectory}

原文地址:https://www.cnblogs.com/king10086/p/12143623.html