winforms 如何处理SystemInvalidOperationException序列中不包含元素'?

smdnsysy  于 2022-11-17  发布在  其他
关注(0)|答案(2)|浏览(196)
private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            string rootPath = Environment.ExpandEnvironmentVariables(@"d:\downloads\main");

            DirectoryInfo directory = new DirectoryInfo(rootPath).GetDirectories()
                .OrderByDescending(d => d.CreationTimeUtc)
                .First();

            Editor editor = new Editor();
            editor.Show();
        }

异常发生在以下行:

DirectoryInfo directory = new DirectoryInfo(rootPath).GetDirectories()
                    .OrderByDescending(d => d.CreationTimeUtc)
                    .First();

我是否应该检查该行中非空或null内容?当rootPath为空时会发生这种情况。

dfty9e19

dfty9e191#

你应该做更多的检查。这个问题是从DirectoryInfo模型开始的。正如你提到的,你必须检查路径是否不为空,而且你还需要检查目录是否真的存在。

string path = "";
        if (string.IsNullOrWhiteSpace(path))
        {
            //do something
        }

        DirectoryInfo directory = new DirectoryInfo(path);
        if (!directory.Exists)
        {
            //do something
        }
sy5wg1nm

sy5wg1nm2#

下面是如何在C#中处理异常:https://www.c-sharpcorner.com/article/csharp-try-catch/
在您的情况下,可以使用FirstOrDefault()代替First,这样就可以返回null
这里只为你:

private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string rootPath = Environment.ExpandEnvironmentVariables(@"d:\downloads\main");

                DirectoryInfo? directory = new DirectoryInfo(rootPath).GetDirectories()
                    .OrderByDescending(d => d.CreationTimeUtc)
                    .FirstOrDefault();

                if (directory is null)
                {
                    if (string.IsNullOrEmpty(rootPath))
                        throw new Exception("Root path was empty.");
                    throw new DirectoryNotFoundException("Directory not found.");
                }

                Editor editor = new Editor();
                editor.Show();
            }catch(DirectoryNotFoundException dirEx)
            {
                MessageBox.Show(dirEx.Message);
                return;
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

相关问题