如何在C#中从try/catch/finally返回?

如何在C#中从try/catch/finally返回?,c#,exception-handling,try-catch,C#,Exception Handling,Try Catch,如果在try/catch/finally中返回不被视为结构化编程,那么如何从下面的代码块返回 public static string ReadFile() { StreamReader streamReader = null; try { try { streamReader = new StreamReader(@"C:\Users\Chir

如果在try/catch/finally中返回不被视为结构化编程,那么如何从下面的代码块返回

        public static string ReadFile()
    {
        StreamReader streamReader = null;
        try
        {
            try
            {
                streamReader = new StreamReader(@"C:\Users\Chiranjib\Downloads\C# Sample Input Files\InputParam.txt"); //Usage of the Verbatim Literal
                return streamReader.ReadToEnd();
            }
            catch (FileNotFoundException exfl)
            {
                string filepath = @"C:\Users\Chiranjib\Downloads\C# Sample Input Files\LogFiles.txt";
                if (File.Exists(filepath))
                {
                    StreamWriter sw = new StreamWriter(filepath);
                    sw.WriteLine("Item you are searching for {0} just threw an {1} error ", exfl.FileName, exfl.GetType().Name);
                    Console.WriteLine("Application stopped unexpectedly");
                }
                else
                {
                    throw new FileNotFoundException("Log File not found", exfl);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                return string.Empty;
            }
            //Code inside finally gets executed even if the catch block returns when an exception happens 
            finally
            {
                //Resource de-allocation happens here
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                Console.WriteLine("Finally block executed");
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine("Log file not found ");
            Console.WriteLine("Original exception " + ex.GetType().Name);
            Console.WriteLine("Inner Exception " + ex.InnerException.GetType().Name);
        }
        finally
        {
            if (streamReader != null)
            {
                streamReader.Close();
            }
            Console.WriteLine("Finally block executed");
        }
        return streamReader.ReadToEnd() ?? string.Empty;
    }
问题是,如果我在获取streamReader对象的值之前关闭它,我将无法获得返回的结果。 但是,这也不允许我最终投入回报


请以标准的方式帮助我理解并克服这个困难。

解决这个问题最简单的方法就是在代码中声明一个变量,然后在最后读出它

比如说

public static string ReadFile()
    {
        var stringFile = "";
        StreamReader streamReader = null;
        try
        {
            try
            {
                streamReader = new StreamReader(@"C:\Users\Chiranjib\Downloads\C# Sample Input Files\InputParam.txt"); //Usage of the Verbatim Literal
                stringFile = streamReader.ReadToEnd();
                return stringFile
            }
            catch (FileNotFoundException exfl)
            {
                string filepath = @"C:\Users\Chiranjib\Downloads\C# Sample Input Files\LogFiles.txt";
                if (File.Exists(filepath))
                {
                    StreamWriter sw = new StreamWriter(filepath);
                    sw.WriteLine("Item you are searching for {0} just threw an {1} error ", exfl.FileName, exfl.GetType().Name);
                    Console.WriteLine("Application stopped unexpectedly");
                }
                else
                {
                    throw new FileNotFoundException("Log File not found", exfl);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                return string.Empty;
            }
            //Code inside finally gets executed even if the catch block returns when an exception happens 
            finally
            {
                //Resource de-allocation happens here
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                Console.WriteLine("Finally block executed");
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine("Log file not found ");
            Console.WriteLine("Original exception " + ex.GetType().Name);
            Console.WriteLine("Inner Exception " + ex.InnerException.GetType().Name);
        }
        finally
        {
            if (streamReader != null)
            {
                streamReader.Close();
            }
            Console.WriteLine("Finally block executed");
        }
        return stringFile;
    }
然后通过执行以下代码读取您的文件

static void Main(string[] args)
{
    var file = ReadFile();
    Console.WriteLine(file);
    Console.ReadLine();
}

我认为您可以消除一些try/catch序列,并通过使用“using”语句来处理StreamWriter和StreamReader。下面是一个例子:

using System;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileContents = ReadFile();
            Console.ReadLine();  // cause program to pause at the end
        }

        public static string ReadFile()
        {
            try
            {
                using (var streamReader = new StreamReader(
                    @"C:\MyTestFile.txt"))
                {
                    var fileContents = streamReader.ReadToEnd();
                    Console.WriteLine("File was read successfully");
                    return fileContents;
                }
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                LogReadFileException(fileNotFoundException);
            }
            catch (DirectoryNotFoundException directoryNotFoundException)
            {
                LogReadFileException(directoryNotFoundException);
            }
            catch (IOException ioException)
            {
                LogReadFileException(ioException);
            }
            // If we get here, an exception occurred
            Console.WriteLine("File could not be read successfully");
            return string.Empty;
        }

        private static void LogReadFileException(Exception exception)
        {
            string logFilePath = @"C:\MyLogFile.txt";

            using (var streamWriter = new StreamWriter(logFilePath, 
                append: true))
            {
                var errorMessage = "Exception occurred:  " +
                    exception.Message;
                streamWriter.WriteLine(errorMessage);
                Console.WriteLine(errorMessage);
            }
        }
    }
}