[英]Environment.CurrentDirectory returns correct path from exe, but not from IDE
我的项目文件夹中有几个文件,在 [myproject]/images
当我运行我的 C# 应用程序时,我在构建后将这些复制到 [myproject]/Debug/images...
当我运行应用程序时, Environment.CurrentDirectory
返回正确的路径
但是,在 IDE 中,当我编辑 WPF 模板时,它不会返回正确的目录
var path = System.IO.Path.Combine(Environment.CurrentDirectory, "images", "someimage.png");
var uri = new Uri(path);
imageSource = new BitmapImage(uri);
我也试过这个:
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
更糟糕的是,它出现在我的文档和设置中
如何计算 IDE 中的正确文件夹路径?
[编辑:]
解决方法,所以我在 XAML 编辑器中没有遇到异常
try
{
Uri uri = new Uri("pack://application:,,,/images/someimage.png");
if (uri != null)
{
someimage= new BitmapImage(uri);
...
}
}
catch (IOException e)
{
...
}
catch (NullReferenceException e)
{
...
}
如果使用UriKind.Relative
(相对于当前目录),你可以完全不使用 .exe 路径
var path = System.IO.Path.Combine("images", "some_image.png");
var uri = new Uri(path, UriKind.Relative);
如果您希望它在 ide 中工作,那么这意味着图像应该获取特定文件,并且可以在 xaml 中设置。
我创建了一个 wpf 解决方案并添加了一个名为 Images 的文件夹。 将我在磁盘上的一个名为 tricorn.jpg 的 jpg 文件拖到该文件夹中。
我将该文件的属性设置为构建操作内容,复制到 output 目录总是复制。 这意味着当我按 f5 时它将被复制到调试/图像文件夹中。
我的标记:
Title="MainWindow" Height="450" Width="800">
<Grid>
<Image Name="img" Source="/Images/tricorn.jpg"/>
</Grid>
</Window>
还有我的设计师的帽子。
如果我将那个 source= 从标记中取出,那就不用帽子了。 明显地。
然后我编辑主窗口ctor:
public MainWindow()
{
InitializeComponent();
img.Source = new BitmapImage(
new Uri("/Images/tricorn.jpg",
UriKind.Relative));
}
在我按下 f5 并运行应用程序之前,仍然看不到帽子。
它在运行时存在于正在运行的 window 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.