为什么我的绝对路径有效,但我的相对路径不是?

时间:2017-04-24 07:45:09

标签: c# uri

我在画布上显示图像。当使用绝对路径时,一切都很完美。但是,当我尝试使用相对路径时,我的代码会运行,但图像未加载。我需要使用相对路径,因为我们正在使用git处理组项目。带有我图像的文件夹位于项目文件夹中。

private void ShuffleCardsClick(object sender, RoutedEventArgs e)
    {
        computerDeck.ShuffleDeck();
        playerDeck.ShuffleDeck();            
        dealButton.IsEnabled = true;

        BitmapImage bi = new BitmapImage();
        bi.BeginInit();            
        bi.UriSource = new Uri(@"card_images\cardback.png", UriKind.RelativeOrAbsolute);

        bi.UriSource = new Uri(@"C:\Users\Windows\Documents\GitHub\NetEssentials_H1\
        Kaartspelen\KoetjeMelken\card_images\cardback.png");
        bi.EndInit();

        Image card = new Image();
        card.Source = bi;
        card.Margin = new Thickness(0, 0, 0, 0);
        card.Width = computerDeckCanvas.Width;
        card.Height = computerDeckCanvas.Height;
        computerDeckCanvas.Children.Add(card);

    }

2 个答案:

答案 0 :(得分:2)

.NET客户端应用程序中的相对路径始终相对于您的工作目录。默认情况下,如果从Visual Studio中运行应用程序,则工作目录为bin \ Debug(如果在Release模式下运行,则为bin \ Release)。

因此,最快的解决方法是指定Visual Studio应将文件复制到目标文件夹。但是,如果用户想要使用不同的工作目录执行程序,则无法解决您的问题。如果要避免在该场景中发生崩溃,则必须计算图像文件的绝对路径,例如以执行程序集的绝对路径为基础。

否则,您还可以将图像包含为资源。

答案 1 :(得分:0)

如果您正在使用MVC项目,那么您可以使用Server.MapPath("your/path")来为您创建相对路径。

更多信息:MSDN

同样对于类库,我之前使用了以下内容:

var appDomain = System.AppDomain.CurrentDomain;
var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
var path = Path.Combine(basePath, "EmailTemplates");