I have a couple of files in my project folder, in [myproject]/images
When I run my C# app, I post-build copy these to [myproject]/Debug/images...
as I run the app, Environment.CurrentDirectory
returns the correct path
but, inside the IDE, it does not return the correct directory when I edit the WPF template
var path = System.IO.Path.Combine(Environment.CurrentDirectory, "images", "someimage.png");
var uri = new Uri(path);
imageSource = new BitmapImage(uri);
I also tried this:
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
it's even worst since it lands in my documents and settings
how can I figure the correct folder path inside the IDE?
[edit:]
workaround, so I dont get an exeption in the XAML editor
try
{
Uri uri = new Uri("pack://application:,,,/images/someimage.png");
if (uri != null)
{
someimage= new BitmapImage(uri);
...
}
}
catch (IOException e)
{
...
}
catch (NullReferenceException e)
{
...
}
you can do without.exe path at all, if use UriKind.Relative
(relative to the current directory)
var path = System.IO.Path.Combine("images", "some_image.png");
var uri = new Uri(path, UriKind.Relative);
If you want this to work in the ide then that means the image should be getting a specific file and that can be set in xaml.
I created a wpf solution and added a folder called Images. Dragged a jpg I had lying about on disk called tricorn.jpg into that folder.
I set that file's properties to Build Action Content, Copy to output directory Copy always. Meaning it will be copied into debug/Images folder when I hit f5.
My markup:
Title="MainWindow" Height="450" Width="800">
<Grid>
<Image Name="img" Source="/Images/tricorn.jpg"/>
</Grid>
</Window>
And there's my hat in the designer.
If I take that source= out of the markup, no hat. Obviously.
I then edit the mainwindow ctor:
public MainWindow()
{
InitializeComponent();
img.Source = new BitmapImage(
new Uri("/Images/tricorn.jpg",
UriKind.Relative));
}
Still no hat visible until I hit f5 and run the app.
It's there at run time in the running window.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.