[英]C# Handle file errors
I am trying to open a file, and I would like to return eg X if the filepath does not exist, Y if the file can't be opened, and Z if it was successful.我正在尝试打开一个文件,如果文件路径不存在,我想返回例如 X,如果文件无法打开,则返回 Y,如果成功则返回 Z。
However, I can't understand how I can check for the "file can't be opened" error and I am not sure my try-catch is correct so far.但是,我不明白如何检查“文件无法打开”错误,并且我不确定我的 try-catch 到目前为止是否正确。 I would also like to add another statement to check if the file is already open.
我还想添加另一个语句来检查文件是否已经打开。
public int Opener(string fileName)
{
string text = "";
try
{
text = File.ReadAllText(fileName);
return "Something to Return";
}
catch (FileNotFoundException)
{
return "Something to Return";
}
You can use this to check the cases you described:您可以使用它来检查您描述的情况:
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
}
}
The function is declared to return an int
, so you need a number there, like -1, 0, or 1. If you want to return a text error message, change the function return type to string
. function 被声明为返回一个
int
,因此您需要一个数字,例如 -1、0 或 1。如果要返回文本错误消息,请将 function 返回类型更改为string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.