gpt4 book ai didi

c# - C#处理文件错误

转载 作者:行者123 更新时间:2023-12-03 08:17:03 25 4
gpt4 key购买 nike

我正在尝试打开文件,并且想返回例如如果文件路径不存在,则为X;如果无法打开文件,则为Y;如果成功,则为Z。
但是,我不明白如何检查“文件无法打开”错误,并且目前尚不确定我的try-catch是否正确。我还想添加另一条语句来检查文件是否已经打开。

public int Opener(string fileName)
{
string text = "";

try
{
text = File.ReadAllText(fileName);
return "Something to Return";
}
catch (FileNotFoundException)
{
return "Something to Return";
}

最佳答案

您可以使用它来检查您描述的情况:

try
{
string text = File.ReadAllText(fileName);

//Z: reading was successful
}
catch (Exception ex)
{
if (ex.InnerException is IOException)
{
//Y: file is already being read
}
else if (ex.InnerException is FileNotFoundException)
{
//X: file does not exist
}
}

关于c# - C#处理文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65218812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com