Best way to handle errors when opening file

时光怂恿深爱的人放手 提交于 2019-12-23 03:39:07

问题


Handling files (opening) is an activity particularly prone to error.

If you were to write a function to do this (although trivial), what is the best way to write it in wrt handling errors?

Is the following good?

if (File.Exists(path))
{ 
    using (Streamwriter ....)
    { // write code }
}

else
// throw error if exceptional else report to user

Would the above (although not syntactially correct) a good way to do this?


回答1:


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.




回答2:


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)




回答3:


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;
    }


来源:https://stackoverflow.com/questions/9503884/best-way-to-handle-errors-when-opening-file

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