Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File io C#:是否正在使用StreamReader并尝试最终处理坏选项?_File Io_C# 2.0_Dispose_Idisposable_Using - Fatal编程技术网

File io C#:是否正在使用StreamReader并尝试最终处理坏选项?

File io C#:是否正在使用StreamReader并尝试最终处理坏选项?,file-io,c#-2.0,dispose,idisposable,using,File Io,C# 2.0,Dispose,Idisposable,Using,想想这个: StreamReader reader = null; try { reader = new StreamReader(_fileName); } catch { //show error that file not found reader.Dispose(); return false; } try { //code to read file } catch { //show error badly formed file } f

想想这个:

StreamReader reader = null;

try
{
    reader = new StreamReader(_fileName);
}
catch
{
    //show error that file not found
    reader.Dispose();
    return false;
}

try
{
    //code to read file
}
catch
{
   //show error badly formed file
}
finally
{
    reader.Dispose();
}
//return 
当文件无法打开时,上面的代码不起作用,因为它调用Dispose for null,这会导致异常

我不想使用using,因为我想把打开文件和读取文件的问题分开。这可以通过百万次不同的捕获来实现,但我不想这样做。另外,如果使用与try finally相同,“hidden Dispose”会抛出一个不需要的异常吗?当我只需要捕获打开它的异常和读取它的异常时,哪种方法是最好的

谢谢&BR-Matti

最好使用:

编译器将为您创建正确的dispose语义

您仍然可以使用
尝试
,而不用担心自己处理它:

try
{
    using(StreamReader reader = new StreamReader(_fileName))
    {
         try
         {
            //code to read the file
         }
         catch
         {
            //show error badly formed file
         }
    }
}
catch
{
    // show error that file not found
}

如果在调用读取器所在的任何方法之前检查读取器是否为null,则代码是正确的


Using语句不是强制性的,但它是可取的。

在处理读卡器之前,应该检查读卡器是否为空。像这样:

StreamReader reader = null;
try
{
    //code to read file
}
catch
{
   //show error badly formed file
}
finally
{
  if( null != reader )
  {
    reader.Dispose();
  }
}

StreamReader
可以抛出以下异常,因此您可以相应地处理这些异常:-

ArgumentException ArgumentNullException FileNotFoundException DirectoryNotFoundException NotSupportedException ArgumentOutOfRangeException 论据例外 无参数异常 FileNotFoundException DirectoryNotFoundException 冒号 ArgumentOutOfRange异常
我现在要做的是在调用Dispose之前在第一个catch if(reader==null)中进行测试……我一直使用using来处理所有IDisposable。但在本例中,我想将错误打开和读取文件分开。您的使用示例只有一个问题。我必须捕捉到许多异常,然后总结出哪个是从开始抛出的,哪个是从开始抛出的reading@matti这取决于您愿意嵌套代码的深度。你可以在using块中使用try catch块。我怎么会如此愚蠢。我在其他地方对所有ADO.NET类(DbConnection、DbDataReader等)使用了相同的结构,很抱歉浪费您的时间。 ArgumentException ArgumentNullException FileNotFoundException DirectoryNotFoundException NotSupportedException ArgumentOutOfRangeException