Dinoswarleafs Dinoswarleafs - 20 days ago 8
C# Question

How can I make Image.FromFile use my application folder?

Right now I'm making a program that changes the picture in a picturebox based on a combo box selection. It works how it should, but if I wanted to export this and send it to friends, it won't work since the only way I've got it to work is using exact file name (which includes my user directory). Despite all the resources being in the Resource folder, if I just give the file name it gives the FileNotFoundException.

I'm pretty new to programming, so specific instructions would be greatly appreciated.

public Form1()
{

InitializeComponent();


MapList();
}

public void MapList()
{
cBox.Items.Add(
new Map() {Name= "Cache" ,
Image = @"C:\Users\Pampperin\Desktop\Videos\Coding\Projects\CSGO Audio Help\MinimapSoundDisplay\MinimapSoundDisplay\Resources\de_cache_radar.png"
});
cBox.Items.Add(
new Map()
{
Name = "Cobblestone",
Image = @"C:\Users\Pampperin\Desktop\Videos\Coding\Projects\CSGO Audio Help\MinimapSoundDisplay\MinimapSoundDisplay\Resources\de_cbble_radar.png"
});
cBox.Items.Add(
new Map()
{
Name = "Dust2",
Image = @"C:\Users\Pampperin\Desktop\Videos\Coding\Projects\CSGO Audio Help\MinimapSoundDisplay\MinimapSoundDisplay\Resources\de_dust2_radar.png"
});
cBox.Items.Add(
new Map()
{
Name = "Inferno",
Image = @"C:\Users\Pampperin\Desktop\Videos\Coding\Projects\CSGO Audio Help\MinimapSoundDisplay\MinimapSoundDisplay\Resources\de_inferno_radar.png"
});
cBox.Items.Add(
new Map()
{
Name = "Mirage",
Image = @"C:\Users\Pampperin\Desktop\Videos\Coding\Projects\CSGO Audio Help\MinimapSoundDisplay\MinimapSoundDisplay\Resources\de_mirage_radar.png"
});
cBox.Items.Add(
new Map()
{
Name = "Nuke",
Image = @"C:\Users\Pampperin\Desktop\Videos\Coding\Projects\CSGO Audio Help\MinimapSoundDisplay\MinimapSoundDisplay\Resources\de_nuke_radar.png"
});
cBox.Items.Add(
new Map()
{
Name = "Overpass",
Image = "Resources.de_overpass_radar.png"
});
}


private void cBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox.SelectedIndex > -1)
{
var imageName = ((Map)cBox.SelectedItem).Image;
var file = System.IO.Path.Combine(Application.StartupPath, "Resources", imageName);
pictureBox.Image = Image.FromFile(file);
}
}


and the Maps class

public class Map
{
public string Name { get; set; }
public string Image { get; set; }
public override string ToString()
{
return this.Name;
}
}

Answer

This gives you the application path:

string apppath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

I didn't test, but alternatively this should work (to keep you from using reflection):

string apppath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);

and then you should be able to set the filenames as such:

Image = System.IO.Path.Combine(apppath, "de_cache_radar.png");