Exception handling

In any real-world scenario, multiple people might be working with the same file concurrently. Using threading in C#, we can lock objects while a particular operation is happening on a resource. However, such locking is not available on files present in the filesystem. 

So, it's quite possible that files that are being accessed in the program have been moved or even deleted altogether by a different application or user. C# provides some exceptions with which we can handle such scenarios in a better way. Please refer to the following code implementation, where we are handling an exception:

private static string ReadFileText()
{
string path =@"C:UCN Code BaseProgramming-in-C-Exam-70-483-MCSD- GuideBook70483SamplesChapter 20Sample.txt";
if (File.Exists(path))
{
try
{
return File.ReadAllText(path);
}
catch (DirectoryNotFoundException)
{
return string.Empty;
}
catch (FileNotFoundException)
{
return string.Empty;
}
}
return string.Empty;
}

From a functionality perspective, in the preceding code we are reading file present in the given location. We are retrieving all the text present in the file and then passing it back to the calling function. Please also note the following best practices that we are using in the code implementation:

  • In the code, we are first checking whether the file exists in the directory location using the Exists method. If the file exists, we proceed to extract data from the file.
  • Even though we have checked that the file exists before we proceed, there are still some circumstances in which the file is removed, deleted, or becomes inaccessible after the code moves to the next block. To handle such scenarios, we are catching the DirectoryNotFoundException and FileNotFoundException exceptions. DirectoryNotFoundException is thrown when the directory specified in the path no longer exists. FileNotFoundException is thrown when the file specified in the path no longer exists. 

Now that we have a fair understanding of how to execute I/O operations on a file, we will look at examples of calling external web services to get a response from them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.236