c#:无法从winforms中的文本文件为PictureBox指定图像源路径
本文关键字:PictureBox 图像 路径 文件 文本 winforms | 更新日期: 2023-09-27 18:11:41
我试图动态地显示PictureBox
中的图像。图像源存储在一个文本文件中。当从文件中读取图像路径时,它一直显示图像错误符号。当我在代码中包含路径时,它就工作了。
文本文件行示例
F01,Nasi Lemak,RM 2,@"Food'NasiLemak.jpg"
public void readData()
{
try
{
int i = 0;
foreach (string line in File.ReadAllLines("food.txt"))
{
string[] parts = line.Split(',');
foreach (string part in parts)
{
Console.WriteLine("{0}:{1}", i, part);
{
Label LblFId = new Label();
{
//LblFId.AutoSize = true;
LblFId.Size = new System.Drawing.Size(70, 20);
}
Label LblFName = new Label();
{
LblFName.Size = new System.Drawing.Size(70, 20);
}
Label LblFPrice = new Label();
{
LblFPrice.Size = new System.Drawing.Size(70, 20);
}
PictureBox foodPicBox = new PictureBox();
{
foodPicBox.Size = new System.Drawing.Size(200, 200);
foodPicBox.SizeMode = PictureBoxSizeMode.StretchImage;
foodPicBox.BorderStyle = BorderStyle.Fixed3D;
}
Panel fPanel = new Panel();
LblFId.Text = parts[0];
LblFName.Text = parts[1];
LblFPrice.Text = parts[2];
foodPicBox.ImageLocation = parts[3];
fPanel.Controls.Add(LblFId);
fPanel.Controls.Add(LblFName);
fPanel.Controls.Add(LblFPrice);
fPanel.Controls.Add(foodPicBox);
foodFlow.Controls.Add(fPanel);
}
}
i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
问题出在文本文件的路径
@"Food'NasiLemak.jpg"
应该像这样保存,不带@和"
"Food'NasiLemak.jpg
或者你应该写更多的代码来删除这些符号,像这样
foodPicBox.ImageLocation = parts[3].Replace("@", "").Replace("'"", "");
这样可以去掉样品,你的问题就解决了。
您还需要在此时关闭foreach语句
foreach (string part in parts)
{Console.WriteLine("{0}:{1}", i, part);}