阅读量:116
在C#中处理文件操作错误,通常需要使用try-catch语句来捕获异常。以下是一些常见的文件操作错误及其处理方法:
- FileNotFoundException:当尝试访问不存在的文件时引发此异常。
try
{
string path = "non_existent_file.txt";
using (StreamReader reader = new StreamReader(path))
{
// 读取文件内容的代码
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("文件未找到: " + ex.Message);
}
- DirectoryNotFoundException:当尝试访问不存在的目录时引发此异常。
try
{
string path = "non_existent_directory";
using (StreamReader reader = new StreamReader(path))
{
// 读取文件内容的代码
}
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("目录未找到: " + ex.Message);
}
- UnauthorizedAccessException:当尝试访问受保护的文件或目录且没有足够的权限时引发此异常。
try
{
string path = "protected_file.txt";
using (StreamReader reader = new StreamReader(path))
{
// 读取文件内容的代码
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("访问被拒绝: " + ex.Message);
}
- PathTooLongException:当尝试操作过长的文件路径时引发此异常。
try
{
string path = new string('a', 26000); // 创建一个过长的路径
using (StreamReader reader = new StreamReader(path))
{
// 读取文件内容的代码
}
}
catch (PathTooLongException ex)
{
Console.WriteLine("路径过长: " + ex.Message);
}
- IOException:当发生其他I/O错误时引发此异常。
try
{
string path = "file.txt";
using (StreamReader reader = new StreamReader(path))
{
// 读取文件内容的代码
}
}
catch (IOException ex)
{
Console.WriteLine("I/O错误: " + ex.Message);
}
在处理文件操作时,务必确保使用try-catch语句捕获可能的异常,并根据需要采取适当的措施。同时,可以使用using语句确保文件在读取或写入后正确关闭。