从目录中读取图像并在屏幕上显示它们

时间:2013-08-14 07:16:30

标签: c#

我可以使用foreach到达目录但是,因为像堆栈一样工作,我只能到达目录中的最后一张图片。我有很多图像从1.jpg开始直到100。

namespace deneme_readimg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {  
            DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");

            foreach (FileInfo file in dir.GetFiles())
            textBox1.Text = file.Name; 
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

4 个答案:

答案 0 :(得分:1)

我不确定你在问什么或者你想要实现什么,但如果你想看到所有的名字,你可以将foreach循环改为:

foreach (FileInfo file in dir.GetFiles())
    textBox1.Text = textBox1.Text + " " + file.Name; 

答案 1 :(得分:0)

仅显示文件名。使用多行文本框

StringBuilder sb = new StringBuilder();
foreach (FileInfo file in dir.GetFiles())       
   sb.Append(file.Name + Environment.NewLine); 

textBox1.Text =sb.ToString().Trim();

如果您想要显示图片,则需要使用ListBoxDataGridView等数据信息,并为每张图片添加行。

答案 2 :(得分:0)

只需收集StringBuilder中输出所需的所有数据; 准备好发布时:

DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");

// Let's collect all the file names in a StringBuilder
// and only then assign them to the textBox. 
StringBuilder Sb = new StringBuilder();

foreach (FileInfo file in dir.GetFiles()) {
  if (Sb.Length > 0) 
    Sb.Append(" "); // <- or Sb.AppendLine(); if you want each file printed on a separate line

  Sb.Append(file.Name);
}

// One assignment only; it prevents you from flood of "textBox1_TextChanged" calls
textBox1.Text = Sb.ToString(); 

答案 3 :(得分:0)

根据@LarsKristensen的建议,我发表评论作为答案。

我会使用AppendText方法,除非您要求在每次点击时添加到文本框,我首先会调用Clear

namespace deneme_readimg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {  
            DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");

            // Clear the contents first
            textBox1.Clear();
            foreach (FileInfo file in dir.GetFiles())
            {
                // Append each item
                textBox1.AppendText(file.Name); 
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}