Relative path to file in Solution Explorer

| September 30, 2010 | 0 Comments

You have solution created in C# or in WPF. To this solution you have added a new folder named Images or something else. And to this folder you have added a file named car.jpg. Now you want to access same file in your application. In the following article we are going to share how to set Relative path to file in Solution Explorer.

This article is been divided in two sections. One is intended for C# and second one for WPF. But the one concept is common in both that we have set the respective file(car.jpg) property Copy to Output Directory as Copy Always. This would ensure that respective file would get copy to …/bin/Debug folder automatically along with its folder structure.

Code Snippet for C#

private void Form1_Load(object sender, EventArgs e)
            pictureBox1.Image = Image.FromFile(Environment.CurrentDirectory + "//Images//car.jpg");

Code Snippet for WPF

private void Window_Loaded(object sender, RoutedEventArgs e)
            var uri = new Uri(Environment.CurrentDirectory + "//Images//car.jpg");

            BitmapImage img = new BitmapImage();
            img.UriSource = uri;

            // image1 is name of Image tag in .xaml
            image1.Source = img;

Note: WPF solution was developed in VS 2010. So you would need to set an extra property Build Action as Content.

When the solution gets compiled successfully you would see the same file with folder structure in …/bin/Debug folder. But if you have relative path to some database file & you don’t want it to change always since it have records in it. In that case you can set the property Copy to Output Directory as Copy If newer.


Category: .NET

Leave a Reply

Sex Chat Live Jasmin WP-Clear 3.0 Theme
%d bloggers like this: