首页 > 解决方案 > 如何在 try catch 块中返回 IEnumerable 对象?

问题描述

我有一个方法,它从目录中读取所有文件作为字符串,然后遍历这些文件以获取文件内容以及其他详细信息并IEnumerable<DataFiles>从中返回一个对象,如下所示:

public IEnumerable<DataFiles> GetFiles(string path)
{
    var listOfFiles = new List<string>();
    try
    {
        var jsonDataFiles = Directory.GetFiles(path, "*.json", SearchOption.AllDirectories);
        var textDataFiles = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
        listOfFiles.AddRange(jsonDataFiles);
        listOfFiles.AddRange(textDataFiles);
        for (int i = 0; i < listOfFiles.Count; i++)
        {
            var cfgPath = listOfFiles[i];
            if (!File.Exists(cfgPath)) { continue; }
            var fileContent = File.ReadAllText(cfgPath);
            var pieces = cfgPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
            var fileName = pieces[pieces.Length - 1];
            var md5HashValue = GetMD5Hash(cfgPath);
            // error on below line
            yield return new DataFiles
            {
                FileName = fileName,
                FileContent = fileContent,
                MD5Hash = md5HashValue
            };
        }
    }
    catch (UnauthorizedAccessException ex)
    {
        // log error here
    }
    // error on below line
    return null;
}

yield return new但不知何故,我return null在上面的方法中遇到了编译错误。以下是我看到的错误:

Cannot yield a value in the body of a try block with a catch clause
Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.

如果上面的代码抛出异常,那么我想返回空IEnumerable<DataFiles>对象,否则它应该返回IEnumerable<DataFiles>包含数据的正确对象`。

我在这里做错了什么?有没有更好更干净的方法来编写上述方法,这样我就不必在方法结束时返回 null ?

标签: c#asp.net-coreienumerable

解决方案


正如 Jamiec 所提到的,您应该能够省略“返回 null”未经授权的异常通常是文件系统错误,因此请事先获取所有文件。还有第二个 try catch 块,以防您的处理出错

public IEnumerable<DataFiles> GetFiles(string path)
    {
        var listOfFiles = new List<string>();
        try
        {
            listOfFiles.AddRange(System.IO.Directory.GetFiles(path, "*.json", System.IO.SearchOption.AllDirectories));
            listOfFiles.AddRange(System.IO.Directory.GetFiles(path, "*.txt", System.IO.SearchOption.AllDirectories));
        }
        catch (UnauthorizedAccessException ex)
        {
            // log error here
        }
        string fileName, fileContent;
        int md5HashValue; // im assuming this is an it, not sure
        //byte[] md5HashValue; // not sure
        for (int i = 0; i < listOfFiles.Count; i++)
        {
            try
            {
                var cfgPath = listOfFiles[i];
                if (!System.IO.File.Exists(cfgPath)) { continue; }
                fileContent = System.IO.File.ReadAllText(cfgPath);
                var pieces = cfgPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
                fileName = pieces[pieces.Length - 1];
                md5HashValue = GetMD5Hash(cfgPath);
            }
            catch (Exception ex)
            {
                // log other error here
                continue;
            }
            // error on below line
            yield return new DataFiles
            {
                FileName = fileName,
                FileContent = fileContent,
                MD5Hash = md5HashValue
            };
        }
    
    }

推荐阅读