我有以下课程
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
?
答案 0 :(得分:2)
您可以像这样使用var fs = require('fs');
var s3fs = require('s3fs');
var multiparty = require('connect-multiparty'),
multipartyMidleware = multiparty();
var s3fsImpl = new s3fs('blahblah', {
accessKeyId: 'ACCESS_KEY_ID',
secretAccessKey: 'SECRET'
});
:
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) }
}
,您可以找到更多regular logger。
答案 1 :(得分: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而不是SubString
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()