using System;
using System.IO;

namespace CommonHelpers {

//**************************************************************************************************
static class HFile {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/// <exception cref="ArgumentNullException" />
public static bool TryCheckExistence(string filePath,out Exception error)
{
   HArgChecking.VerifyNotNull( filePath );
   try
   {
      if ( (File.GetAttributes( filePath ) & FileAttributes.Directory)!=0 )
         throw new FileNotFoundException(HString.FormatAsText(
            "File not found: \"{0}\".",
            filePath ));
   }
   catch (Exception e)
   {
      error = e;
      return false;
   }
   error = null;
   return true;
}

/// <exception cref="ArgumentNullException" />
/// <exception cref="SystemException" />
/// <exception cref="FileNotFoundException" />
public static bool RemoveReadOnlyFile(string filePath,bool throwIfNotFound=true)
{
   HArgChecking.VerifyNotNull( filePath );
   FileAttributes attr;
   try
   {
      attr = File.GetAttributes( filePath );
   }
   catch (FileNotFoundException)
   {
      if ( throwIfNotFound )
         throw;
      return false;
   }
   if ( (attr & FileAttributes.ReadOnly) != 0 )
      File.SetAttributes( filePath, attr & ~FileAttributes.ReadOnly );
   File.Delete( filePath );
   return true;
}

/// <exception cref="ArgumentNullException" />
/// <exception cref="SystemException" />
public static bool MakeFileReadOnly(string filePath)
{
   var attr = File.GetAttributes( HArgChecking.NotNull( filePath ) );
   if ( (attr & FileAttributes.ReadOnly) == 0 )
   {
      File.SetAttributes( filePath, attr | FileAttributes.ReadOnly );
      return true;
   }
   return false;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // HFile
//**************************************************************************************************

} // CommonHelpers
