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.
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. 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.