2017-06-13 17 views
0

私のベースディレクトリにはイメージ用のフォルダがあります。このフォルダには、イメージが1つしかありません。イメージの名前を取得してImage Sourceにロードします。このコードでは、エラーが発生します:wpfのベースディレクトリ(アプリケーションディレクトリ)内でイメージ名を取得する方法C#

Could not find file'C:\Users\Santhosh\Documents\Visual Studio 2012\imagetest\imagetest\bin\Debug\ImageFolder\System.Linq.Enumerable+WhereSelectArrayIterator`2[System.String,System.String].jpg'

ベースディレクトリからイメージ名を取得するにはどうすればよいですか?

これは私のコード

string ImageFiles=Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory+"\\ImageFolder\\",".jpg").Select(System.IO.Path.GetFileName).ToString(); 
image1.source== new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\ImageFolder\\"+ImageFiles+".jpg")); 
+0

あなたはデバッグフォルダにいますか?このディレクトリにはC:¥Users¥Santhosh¥Documents¥Visual Studio 2012¥imagetest¥imagetest¥bin¥Debug¥ImageFolder? – doremifasolasido

+1

そして、.ToString onを選択しないでください。 – doremifasolasido

+0

はいデバッグフォルダ – santhosh

答えて

1

コールFirstOrDefaultディレクトリが一致する名前を持つファイルが含まれていない場合、最初のディレクトリからファイル、またはnullを得ることです:

var imageFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ImageFolder"); 
var firstFile = Directory.EnumerateFiles(imageFolder, "*.jpg") 
    .Select(Path.GetFileName) 
    .FirstOrDefault(); 

if (firstFile != null) 
{ 
    image.Source = new BitmapImage(new Uri(Path.Combine(imageFolder, firstFile))); 
} 

またはそれより短いです、GetFileNameおよびそれに続くCombineなし:

var imageFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ImageFolder"); 
var firstFile = Directory.EnumerateFiles(imageFolder, "*.jpg") 
    .FirstOrDefault(); 

if (firstFile != null) 
{ 
    image.Source = new BitmapImage(new Uri(firstFile)); 
} 
+0

ありがとう作品 – santhosh

+0

そしてこの画像をディレクトリから削除するには、File.Deleteのコードを書いていますが、画像を削除できません "プロセスはファイルにアクセスできません 'Jackalope_Room_Full.jpg 'それは別のプロセスで使用されているためです。それを削除するには? – santhosh

+0

@santhoshおそらくコメントではなく、別の質問として削除について尋ねるほうがよいでしょう。 –

0

これは次のようになります。

string ImageFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\ImageFolder\\").Select(System.IO.Path.GetFileName).First(); 
+0

ありがとう:)この画像をディレクトリから削除するには、File.Deleteのコードを書きますが、画像を削除することはできませんエラー "プロセスが別のプロセスで使用されているため、 'Jackalope_Room_Full.jpg'ファイルにアクセスできません。それを削除するには? – santhosh

+0

おそらく開いているでしょう。プログラムを実行する前に閉じてください – doremifasolasido