处理I/O错误

将错误代码映射到异常
由于文件系统为操作系统资源,.NET Core 和 .NET Framework 中的 I/O 方法将包装对基础操作系统的调用。 当由操作系统执行的代码出现 I/O 错误时,操作系统将对 .NET I/O 方法返回错误信息。 然后,该方法会将错误信息(通常采用错误代码形式)转换为 .NET 异常类型。 大多数情况下,可以通过直接将错误代码转换为其相应异常类型来完成此操作;它不基于方法调用的上下文执行任何特殊的错误映射。
操作系统返回特定错误代码的精确条件通常未记录或记录不当。 因此,会出现意外异常。
异常类型 .NET Core .NET Framework
IOException
是 是
FileNotFoundException
是 是
DirectoryNotFoundException
是 是
DriveNotFoundException
是 是
PathTooLongException
是 是
OperationCanceledException
是 是
UnauthorizedAccessException
是 是
可以使用 catch 语句中的 When 子句来处理这些问题,如以下示例所示。
using System;
using System.IO;
using System.Text;

class Program
{
static void Main()
{
var sw = OpenStream(@".\textfile.txt");
if (sw is null)
return;
sw.WriteLine(“This is the first line.”);
sw.WriteLine(“This is the second line.”);
sw.Close();
}

static StreamWriter OpenStream(string path)
{
if (path is null) {
Console.WriteLine(“You did not supply a file path.”);
return null;
}

    try {
        var fs = new FileStream(path, FileMode.CreateNew);
        return new StreamWriter(fs);
    }
    catch (FileNotFoundException) {
        Console.WriteLine("The file or directory cannot be found.");
    }
    catch (DirectoryNotFoundException) {
        Console.WriteLine("The file or directory cannot be found.");
    }
    catch (DriveNotFoundException) {
        Console.WriteLine("The drive specified in 'path' is invalid.");
    }
    catch (PathTooLongException) {
        Console.WriteLine("'path' exceeds the maxium supported path length.");
    }
    catch (UnauthorizedAccessException) {
        Console.WriteLine("You do not have permission to create this file.");
    }
    catch (IOException e) when ((e.HResult & 0x0000FFFF) == 32 ) {
        Console.WriteLine("There is a sharing violation.");
    }
    catch (IOException e) when ((e.HResult & 0x0000FFFF) == 80) {
        Console.WriteLine("The file already exists.");
    }
    catch (IOException e) {
        Console.WriteLine($"An exception occurred:\nError code: " +
                          $"{e.HResult & 0x0000FFFF}\nMessage: {e.Message}");
    }
    return null;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值