0

试图弄清为什么它不起作用,列表是使用combobox项目(其中列出本地HDD root地址为项目)检索照片方法但在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;
        }
    }
4

1 回答 1

0

您应该.在行中的文件扩展名之前放置:

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;
    }
}

此外,这可能更适合于方法而不是属性,因为它做了很多处理......

于 2013-11-23T23:16:06.880 回答