2016-12-04 143 views
0

我具有低於類創建每個項目的新對象

public class Photo 
{ 
    public int ShowOrder { get; set; } 
    public string Format { get; set; } 
    public byte[] Image { get; set; } 
} 

我的代碼硬編碼線從一個文件夾加載圖像,將它們添加到類型的變量List<Photo>

var Photos = new List<Photo>() 
{ 
    new Photo() { ShowOrder = 1, Image = File.ReadAllBytes("D:\\Sample\\pic1.jpg")), Format = "jpg" }, 
    new Photo() { ShowOrder = 2, Image = File.ReadAllBytes("D:\\Sample\\pic2.png")), Format = "png" }, 
    new Photo() { ShowOrder = 3, Image = File.ReadAllBytes("D:\\Sample\\pic3.jpg")), Format = "jpg" }, 
    new Photo() { ShowOrder = 4, Image = File.ReadAllBytes("D:\\Sample\\pic4.gif")), Format = "gif" } 
} 

我想讓這部分動態地加載文件夾中的所有照片,而不是硬編碼。

我以爲我可以使用ForEach函數,但無法弄清楚如何。 有沒有辦法使用LINQ來做到這一點?

回答

1

您可以嘗試下面的代碼,它通過文件ext過濾文件,它是LINQ;

// directory path which you are going to list the image files 
var sourceDir = "directory path"; 

// temp variable for counting file order 
int fileOrder = 0; 

// list of allowed file extentions which the code should find 
var allowedExtensions = new[] { 
".jpg", 
".png", 
".gif", 
".bmp", 
".jpeg" 
}; 

// find all allowed extention files and append them into a list of Photo class 
var photos = Directory.GetFiles(sourceDir) 
         .Where(file => allowedExtensions.Any(file.ToLower().EndsWith)) 
         .Select(imageFile => new Photo() 
         { 
          ShowOrder = ++fileOrder, 
          Format = imageFile.Substring(imageFile.LastIndexOf(".")), 
          Image = File.ReadAllBytes(imageFile) 
         }) 
         .ToList(); 

編輯:

我用GetFileExtension代替串

Directory.GetFiles(sourceDir)) 
        .Where(file => allowedExtensions.Any(file.ToLower().EndsWith)) 
        .Select(imageFile => new Photo() 
        { 
         ShowOrder = ++fileOrder, 
         Image = File.ReadAllBytes(imageFile), 
         Format = Path.GetExtension(imageFile) 
        } 
        ).ToList() 
+1

正是我在找的東西。但是我可以使用GetFileExtension而不是Substrting。謝謝。我更新答案。 – FLICKER

2

您可以使用Directory這樣的:

var Photos = new List<Photo>(); 
int itt = 1; 
foreach(var path in Directory.GetFiles(@"D:\Sample")) 
{ 
    Photos.Add(new Photo() {ShowOrder = itt++, Image = File.ReadAllBytes(path)), Format = path.Substring((path.Length - 3), 3) } 
} 

這隻有該文件夾中的所有文件都是圖片,但如果沒有你需要用搜索模式來調整Getfiles()你可以找到更多here

+1

我想你應該將'INT ITT = 1'到'foreach'圈的外側。 –

+0

@RichardSchneider是的,謝謝。 – Emad

+1

您可以使用Path.GetExtension()獲取格式,該格式也適用於所有長度的文件類型,而不僅僅是三個字母。 (如jpeg) – PartlyCloudy

相關問題