public static bool TestFile( [NotNull] string fileLabel, [NotNull] string filename,
bool createIfDoesNotExist, FileAccess neededAccess)
{
if ( fileLabel == null )
throw new ArgumentNullException( "fileLabel" );
if ( filename == null )
throw new ArgumentNullException( "filename" );
try {
new FileInfo( filename );
if ( File.Exists( filename ) ) {
if ( ( neededAccess & FileAccess.Read ) == FileAccess.Read ) {
using ( File.OpenRead( filename ) ) { }
}
if ( ( neededAccess & FileAccess.Write ) == FileAccess.Write ) {
using ( File.OpenWrite( filename ) ) { }
}
} else if ( createIfDoesNotExist ) {
using ( File.Create( filename ) ) { }
}
return true;
} catch ( Exception ex ) {
if ( ex is ArgumentException || ex is NotSupportedException || ex is PathTooLongException ) {
Logger.Log( LogType.Error,
"Paths.TestFile: Specified path for {0} is invalid or incorrectly formatted ({1}: {2}).",
fileLabel, ex.GetType().Name, ex.Message );
} else if ( ex is SecurityException || ex is UnauthorizedAccessException ) {
Logger.Log( LogType.Error,
"Paths.TestFile: Cannot create or write to {0}, please check permissions ({1}: {2}).",
fileLabel, ex.GetType().Name, ex.Message );
} else if ( ex is DirectoryNotFoundException ) {
Logger.Log( LogType.Error,
"Paths.TestFile: Drive/volume for {0} does not exist or is not mounted ({1}: {2}).",
fileLabel, ex.GetType().Name, ex.Message );
} else if ( ex is IOException ) {
Logger.Log( LogType.Error,
"Paths.TestFile: Specified file for {0} is not readable/writable ({1}: {2}).",
fileLabel, ex.GetType().Name, ex.Message );
} else {
throw;
}
}
return false;
}