The Labs \ Source Viewer \ SSCLI \ System.Configuration \ FileUtil

  1. //------------------------------------------------------------------------------
  2. // <copyright file="FileUtil.cs" company="Microsoft">
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. // </copyright>
  14. //------------------------------------------------------------------------------
  15. namespace System.Configuration
  16. {
  17.     using System;
  18.     using System.IO;
  19.     using Microsoft.Win32;
  20.     using System.Runtime.InteropServices;
  21.    
  22.     static internal class FileUtil
  23.     {
  24.         const int HRESULT_WIN32_FILE_NOT_FOUND = unchecked((int)2147942402u);
  25.         const int HRESULT_WIN32_PATH_NOT_FOUND = unchecked((int)2147942403u);
  26.        
  27.         //
  28.         // Use to avoid the perf hit of a Demand when the Demand is not necessary for security.
  29.         //
  30.         // If trueOnError is set, then return true if we cannot confirm that the file does NOT exist.
  31.         //
  32.         static internal bool FileExists(string filename, bool trueOnError)
  33.         {
  34.             UnsafeNativeMethods.WIN32_FILE_ATTRIBUTE_DATA data;
  35.             bool ok = UnsafeNativeMethods.GetFileAttributesEx(filename, UnsafeNativeMethods.GetFileExInfoStandard, out data);
  36.             if (ok) {
  37.                 // The path exists. Return true if it is a file, false if a directory.
  38.                 return (data.fileAttributes & (int)FileAttributes.Directory) != (int)FileAttributes.Directory;
  39.             }
  40.             else {
  41.                 if (!trueOnError) {
  42.                     return false;
  43.                 }
  44.                 else {
  45.                     // Return true if we cannot confirm that the file does NOT exist.
  46.                     int hr = Marshal.GetHRForLastWin32Error();
  47.                     if (hr == HRESULT_WIN32_FILE_NOT_FOUND || hr == HRESULT_WIN32_PATH_NOT_FOUND) {
  48.                         return false;
  49.                     }
  50.                     else {
  51.                         return true;
  52.                     }
  53.                 }
  54.             }
  55.         }
  56.     }
  57. }

Developer Fusion