2016-11-20 44 views
0

現在我正在製作一個程序,根據組合框的選擇更改圖片框中的圖片。它的工作方式應該如何,但是如果我想導出並將其發送給朋友,它將無法工作,因爲我使用它的唯一方法是使用精確的文件名(包括我的用戶目錄)。儘管所有的資源都在Resource文件夾中,但如果我只是給出文件名,它會給出FileNotFoundException。如何讓Image.FromFile使用我的應用程序文件夾?

我很新的編程,所以具體的指示將不勝感激。

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); 
     } 
    } 

和地圖類

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

這些嵌入圖像作爲資源 –

+0

存儲文件的用戶'...'文件夾或也許'計劃Data' - 它幾乎爲什麼存在。你也應該處理前一個圖像(如果有的話) - 如果你創建它,你需要處理它 – Plutonix

回答

0

這給你的應用程序路徑:

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

我沒有測試,但或者這應該工作(讓你使用反射):

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

a第二,那麼你應該可以設置文件名這樣:

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

工作就像一個魅力,謝謝:) – Dinoswarleafs

相關問題