此代码用于从我存储的文本文件中读取文件夹目录,并使用该“activeFilepath”变量读取文件夹中的每个文件并检索其名称,这些名称又可用于加载每个文件依次形成图像。
StreamReader textIn = new StreamReader(imageSet);
try
{
//Get the folder location by reading in the specific text file.
activeFilepath = textIn.ReadLine();
//If the user isn't choosing a password then go into the 'Blurred' directory of the folder.
if (choosePassword == false)
activeFilepath = activeFilepath + @"\Blurred";
int i = 0;
//Read in all of the image location strings, and put them in the pictureLocations list.
foreach (string filePath in Directory.EnumerateFiles(activeFilepath))
{
pictureLocations.Add(filePath);
//pictureLocations[i] = filePath;
// Display an error image if there is a blank entry in the picture location.
if (pictureLocations[i] == null)
pictureLocations[i] = @"C:\Users\Public\Pictures\Sample Pictures\error.png";
//Remove Thumbs.db from the list if read in.
if (pictureLocations[i] == activeFilepath + @"\Thumbs.db")
{
pictureLocations.Remove(pictureLocations[i]);
}
i++;
}
foreach (PictureBox imagePanel in pictureBoxList)
{
int rand = randomGenerator.Next(0, pictureLocations.Count);
//The images are then loaded in a random order from the picture location list.
imagePanel.Load(pictureLocations[rand]);
//Remove the picture just loaded out of the list so it won't repeat.
pictureLocations.Remove(pictureLocations[rand]);
imagePanel.SizeMode = PictureBoxSizeMode.StretchImage;
}
目前我收到一个索引类型错误,说当我从列表中删除Thumbs.db时索引超出范围(因为我不想将它加载到我的表单上的图片框中)但是,当我只是让它读入时,我收到一个参数类型的错误。
我假设我得到了后者,因为它试图将Thumbs.db作为图像加载,但我想知道是否有另一种方法可以删除或阻止它首先被读取? 它完全是另类吗?
答案 0 :(得分:2)
您可以尝试完全从枚举中过滤.db,这样您就不必将其删除。
foreach (string filePath in Directory.EnumerateFiles(activeFilepath, "*.*",
SearchOption.AllDirectories)
.Where(x => Path.GetExtension(x) != ".db"))
{
}
您的代码看起来像这样:
List<string> enumerateFiles = Directory.EnumerateFiles(activeFilepath, "*.*", SearchOption.AllDirectories).ToList();
for (int i = 0; i < enumerateFiles.Count(); i++)
{
String filePath = enumerateFiles[i];
// skip the .db file
if (Path.GetExtension(filePath) != ".db")
{
continue;
}
pictureLocations.Add(filePath);
//pictureLocations[i] = filePath;
// Display an error image if there is a blank entry in the picture location.
if (pictureLocations[i] == null)
pictureLocations[i] = @"C:\Users\Public\Pictures\Sample Pictures\error.png";
}
答案 1 :(得分:2)
即使您没有添加任何内容,崩溃也会增加i
。如果你不想保留它,一个简单的修复就是不添加项目。这样你就不需要讨厌的i
变量。
//Read in all of the image location strings, and put them in the pictureLocations list.
foreach (string filePath in Directory.EnumerateFiles(activeFilepath))
{
// Display an error image if there is a blank entry in the picture location.
if (filePath == null)
filePath = @"C:\Users\Public\Pictures\Sample Pictures\error.png";
//Skip Thumbs.db
if (filePath == activeFilepath + @"\Thumbs.db")
{
continue;
}
pictureLocations.Add(filePath);
}
换句话说,不是添加一个项目然后意识到你并不是要添加它(并且必须跟踪它的位置),而是先决定是否要添加它(和如果需要编辑),然后添加它,如果你想保留它。
这可以避免pictureLocation
和i
之间脆弱的关系。