Best way to handle errors when opening file

这一生的挚爱 提交于 2019-12-07 00:40:30

First you can verify if you have access to the file, after, if the file exists and between the creation of the stream use a try catch block, look:

public bool HasDirectoryAccess(FileSystemRights fileSystemRights, string directoryPath)
{
    DirectorySecurity directorySecurity = Directory.GetAccessControl(directoryPath);

    foreach (FileSystemAccessRule rule in directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
    {
        if ((rule.FileSystemRights & fileSystemRights) != 0)
        {
            return true;
        }
    }

    return false;
}

So:

if (this.HasDirectoryAccess(FileSystemRights.Read, path)
{
    if (File.Exists(path))   
    {  
        try
        {      
            using (Streamwriter ....)       
            { 
                // write code 
            }   
        }
        catch (Exception ex)            
        {    
            // throw error if exceptional else report to user or treat it                          
        } 
    }      
    else
    {
        // throw error if exceptional else report to user   
    }
}

Or you can verify all things with the try catch, and create the stream inside the try catch.

Accessing external resources is always prone to error. Use a try catch block to manage the access to file system and to manage the exception handling (path/file existence, file access permissions and so on)

You can use something like this

    private bool CanAccessFile(string FileName)
    {
        try
        {
            var fileToRead = new FileInfo(FileName);
            FileStream f = fileToRead.Open(FileMode.Open, FileAccess.Read, FileShare.None);
            /*
                 * Since the file is opened now close it and we can access it
                 */
            f.Close();
            return true;
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Cannot open " + FileName + " for reading. Exception raised - " + ex.Message);
        }

        return false;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!