C# 如何在try-catch块中返回IEnumerable对象?

C# 如何在try-catch块中返回IEnumerable对象?,c#,asp.net-core,ienumerable,C#,Asp.net Core,Ienumerable,我有一个方法,它从目录中以字符串形式读取所有文件,然后迭代这些文件以获取文件内容和其他详细信息,并从中返回一个IEnumerable对象,如下所示: public IEnumerable<DataFiles> GetFiles(string path) { var listOfFiles = new List<string>(); try { var jsonDataFiles = Directory.GetFiles(path,

我有一个方法,它从目录中以字符串形式读取所有文件,然后迭代这些文件以获取文件内容和其他详细信息,并从中返回一个
IEnumerable
对象,如下所示:

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;
}
若上面的代码抛出异常,那个么我想返回空的
IEnumerable
对象,否则它应该返回正确的
IEnumerable
对象,其中包含数据

我在这里干什么?有没有更好更干净的方法来编写上述方法,这样我就不必在方法末尾返回null?

执行以下步骤:

  • 在try块外部为
    数据文件
    声明类型化变量
  • 将数据分配给该变量,如下所示:
  • 外部捕获块写为

正如Jamiec提到的,您应该能够省略“returnnull” 未经授权的异常通常是一个文件系统错误,所以请先抓取所有文件。 还有第二个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
            };
        }
    
    }
public IEnumerable GetFiles(字符串路径)
{
var listOfFiles=新列表();
尝试
{
AddRange(System.IO.Directory.GetFiles(路径“*.json”、System.IO.SearchOption.AllDirectories));
AddRange(System.IO.Directory.GetFiles(路径“*.txt”,System.IO.SearchOption.AllDirectories));
}
捕获(未经授权的访问例外)
{
//此处记录错误
}
字符串文件名,文件内容;
int md5HashValue;//我假设这是一个it,不确定
//字节[]md5HashValue;//不确定
for(int i=0;i
您应该能够省略
返回nullyield
,则代码>行。否则,您是否根据错误消息尝试了
产生中断
?但如果抛出异常会发生什么?您的迭代将停止。。。这就是你想要的吗?我更新了我的问题。我忘了添加那个细节。如果抛出异常,我想返回空的
IEnumerable
对象,否则基本上返回正确的
IEnumerable
对象和完整的内容。然后不要使用yield,因为在计算枚举数之前不会抛出错误。我建议建立一个
列表
并返回该值或null。这里使用的是
yield
,这让您感到困惑。谢谢您的建议。这是写上述方法的干净方法吗?我不能说,只是为了确保清洁,只是我喜欢的风格。此外,我通常不会编写收益率语句,因此,对于所有额外的System.IO,这可能无法开箱即用。和名称空间。我劫持了我正在处理的一个文件,不想改变那么多。你可以删除它们,因为我猜你已经把它们包括在内了。我用我的新代码更新了我的问题,其中我只使用列表,但在返回时,我在最后将其标记为
ReadOnly
。你认为这样做也不会有任何问题吗?我最后返回的列表是
IEnumerable
,但是是只读的吗?我认为这会很好地工作(但是通常我30%的假设会在几年后困扰我)我从来没有使用过只读的,我会假设会发生这种情况。我会在事后编写一个测试来进行双重检查,或者找到一些甜美的m-soft文档。
yourDataFilesObj = new DataFiles
                {
                   FileName = fileName,
                   FileContent = fileContent,
                   MD5Hash = md5HashValue
                };

yield return yourDataFilesObj;
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
            };
        }
    
    }