IOException or file check. Exists?

(I searched for similar topics and could not find anything that related to this particular problem, although there were several similar ones, such as here and.)

I evaluate the performance of our application, and I notice that we get some IOExceptions "Unable to find resource." I don’t know exactly how many times this happens (it depends a lot on how the user uses the application), but this is not less than a dozen or so.

I assume that exceptions in general are costly in performance, as are file I / O calls, for example File.Exists(). I know that it is always useful to check if a file exists before trying to download it. My question is: how much can I increase performance if I check if this particular file exists? (Again, ignore "you should do this anyway", I'm just trying to understand the idea of ​​performance).

Option 1:

try
{
    return (ResourceDictionary) Application.LoadComponent(uri);
}
catch (Exception)
{
    //If it not there, don't do anything
}

This does not make an additional I / O call, but sometimes throws an exception that is swallowed.

Option 2 :

if(File.Exists(uri))
{
    return (ResourceDictionary) Application.LoadComponent(uri);
}
+5
source share
3 answers

, ( : ), . , .

, , . , /. , - - , , , , .

+6

, . - , . , , , / . , -

private static Dictionary<Uri, ResourceDictionary> _uriToResources =
  new Dictionary<Uri, ResourceDictionary>();
public static ResourceDictionary GetResourceDictionary(Uri uri)
{
  ResourceDictionary resources;
  if (_uriToResources.TryGetValue(uri, out resources))
  {
    return resources;
  }

  try
  {
     resources = (ResourceDictionary)Application.LoadComponent(uri);
  }
  catch
  {
     // could prompt/alert the user here.
     resources = null; // or an appropriate default.
  }

  _uriToResources[uri] = resources;
  return resources;
}

, . , .

+1

File.Exists . , .

File.cs, , File.Exists.

 [SecurityCritical]
    private static bool InternalExistsHelper(string path, bool checkHost)
    {
      try
      {
        if (path == null || path.Length == 0)
          return false;
        path = Path.GetFullPathInternal(path);
        if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1]))
          return false;
        FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false);
        return File.InternalExists(path);
      }
      catch (ArgumentException ex)
      {
      }
      catch (NotSupportedException ex)
      {
      }
      catch (SecurityException ex)
      {
      }
      catch (IOException ex)
      {
      }
      catch (UnauthorizedAccessException ex)
      {
      }
      return false;
    }
0

All Articles