2012-06-03 46 views
-2

可能重複:
Getting the application's directory from a WPF application獲取文件到指定的文件夾在C#

我想接取從項目目錄中的文件像Java中不使用 「C:\路徑」,因爲它創建文件例外到我的圖片框這是代碼到我的計時器

if (imagecount == 30) 
{ 
    this.pictureBox1.Image = System.Drawing.Image.FromFile(@"C:\Users\Baloi\Documents\visual studio 2010\Projects\WinEX\WinEX\" + image() + ".jpg"); 
    imagecount = 0; 
} 

else if (imagecount < 30) 
    imagecount++; 
+2

你的問題是什麼? – Oded

+0

也類似於:http://stackoverflow.com/questions/3259583/how-to-get-files-in-a-relative-path-in-c-sharp –

回答

2

Aplication directory

string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; 

Executable Directory

string executableDirectory = Path.GetDirectoryName(Application.ExecutablePath); 

根據您的要求,您可以使用與Path.Combine的上述之一,建立你的圖像位置的完整路徑。

或者您可以將圖像嵌入到資源文件中。那麼你可以將它們作爲

Stream imgStream = 
    Assembly.GetExecutingAssembly().GetManifestResourceStream(
    "YourNamespace.resources.ImageName.bmp"); 
pictureBox.Image = new Bitmap(imgStream); 
0

您可以使用代碼:

this.pictureBox1.Image = System.Drawing.Image.FromFile(image() + ".jpg"); 

你的文件應該在同一文件夾中的程序。

+0

謝謝,但圖像是一個整數返回照片的編號 –

+0

FileNotfoundException –

0

您有幾種選擇:

  1. 嵌入在項目中的圖片(設置編譯動作嵌入式數據)

  2. 參考您的圖片使用相對路徑。這是由以下事實,在調試時,二進制組件是在bin \ Debug文件夾

有關選項1稍微複雜:

System.Reflection.Assembly thisExe; 
thisExe = System.Reflection.Assembly.GetExecutingAssembly(); 
System.IO.Stream file = 
    thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg"); 
this.pictureBox1.Image = Image.FromStream(file); 

http://msdn.microsoft.com/en-us/library/aa287676(v=vs.71).aspx

對於選項2:

string appPath = Path.GetDirectoryName(Application.ExecutablePath); 
if (System.Diagnostics.Debugger.IsAttached) 
{ 
    contentDirectory = Path.Combine(appPath + @"\..\..\content"); 
} 
else 
{ 
    contentDirectory = Path.Combine(appPath, @"content"); 
} 
+0

感謝它工作正常我問了Codeproject上的同樣的事情,但人們只看到 –

+0

錯誤picturebox空流 –

相關問題