【问题标题】:List not working upon GetFiles method列表不适用于 GetFiles 方法
【发布时间】:2013-11-23 23:09:11
【问题描述】:

Trying to figure out why this isn't working, the list is to retrieve photos using the combobox item (which lists local HDDs root address as items) when selected that item it is converted into a string and supposed to be used as GetFiles 方法的路径但在运行时在 (string path = ) 行上搞砸了,我得到“对象引用未设置为对象的实例”非常感谢如果有人能告诉我出了什么问题

public List<Photos> LoadImages ///List Retrieves and Loads Photos
    {

        get
        {
            List<Photos> Image = new List<Photos>();
            string path = HDDSelectionBox.SelectedItem.ToString(); //ComboBox SelectedItem Converted To String As Path
            foreach (string filename in Directory.GetFiles(path, "*jpg")) 
            {
                try
                {
                    Image.Add( //Add To List
                        new Photos(
                            new BitmapImage(
                                new Uri(filename)),
                                System.IO.Path.GetFileNameWithoutExtension(filename)));
                }
                catch { } //Skips Any Image That Isn't Image/Cant Be Loaded
            }
            return Image;
        }
    }

【问题讨论】:

  • 这很可能意味着HDDSelectionBoxHDDSelectionBox.SelectedItem 为空。你检查过吗?
  • mm 我读到了,但是因为我正在学习这对我来说是新的,我的目标是仅在组合框不为空时加载图像,即仅在用户选择了一个项目之后从组合框中,我感觉它在程序加载时制作了一个列表,然后当然会以 null 开头

标签: c# wpf list .net getfiles


【解决方案1】:

你应该把.放在文件扩展名之前:

Directory.GetFiles(path, "*.jpg")

你还需要检查HDDSelectionBox.SelectedItem是否不为空:

public List<Photos> LoadImages ///List Retrieves and Loads Photos
{
    get
    {
        List<Photos> images = new List<Photos>();
        if (HDDSelectionBox.SelectedItem != null)
        {
            string path = HDDSelectionBox.SelectedItem.ToString(); //ComboBox SelectedItem Converted To String As Path
            foreach (string filename in Directory.GetFiles(path, "*.jpg"))
            {
                try
                {
                    images.Add( //Add To List
                        new Photos(
                            new BitmapImage(
                                new Uri(filename)),
                                System.IO.Path.GetFileNameWithoutExtension(filename)));
                }
                catch { } //Skips Any Image That Isn't Image/Cant Be Loaded
            }
        }
        return images;
    }
}

此外,这可能更适合于方法而不是属性,因为它会进行大量处理...

【讨论】:

  • 太棒了,我还在徘徊我的新 Lists 行会去哪里?到目前为止,感谢帮助,我曾考虑过一段时间检查 null 但它目前期望一个 get 或 set 访问器加上 if 语句
  • 该行可以在检查毛皮为空之前。如果 HDDSelectionBox.SelectedItem 为 null,它将返回一个空列表。
  • 到目前为止我的公共列表加载图像{然后是新列表();然后是 if,但它在新的 List 行上强调了我
  • 谢谢,代码运行没有错误,但是当我从组合框中选择一个项目时,列表框没有显示任何内容,这可能只是我的绑定,但我已经通过并检查了
  • 单步执行代码时是否返回Photos 列表?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多