C# Class CK.Core.FileUtil

Helper functions related to file system.
Show file Open project: Invenietis/ck-core

Public Properties

Property Type Description
AltDirectorySeparatorString string
DirectorySeparatorString string
FileNameUniqueTimeUtcFormat string
GzipFileHeader byte[]
InexistingFile FileAttributes
MissingFileLastWriteTimeUtc System.DateTime

Public Methods

Method Description
CheckForWriteAccess ( string path, int nbMaxMilliSecond ) : bool

Waits for a file to be writable or does not exist (if it does not exist, it can be created!). The file is opened and close. Waits the number of nbMaxMilliSecond before leaving and returning false: when 0 (the default), there is no wai. A nbMaxMilliSecond below 20 ~ 30 milliseconds is not accurate: even with nbMaxMilliSecond = 1 this method will return true if the file becomes writable during the next 10 or 20 milliseconds.

CompressFileToGzipFile ( string sourceFilePath, string destinationPath, bool deleteSourceFileOnSuccess, CompressionLevel level = CompressionLevel.Optimal, int bufferSize = 64*1024 ) : void

Compresses a file to another file, using GZip at the given compression level.

CompressFileToGzipFileAsync ( string sourceFilePath, string destinationPath, CancellationToken cancellationToken = default(CancellationToken), bool deleteSourceFileOnSuccess = true, CompressionLevel level = CompressionLevel.Optimal, int bufferSize = 64*1024 ) : Task

Compresses a file to another file asynchronously, using GZip at the given compression level.

CopyDirectory ( DirectoryInfo src, DirectoryInfo target, bool withHiddenFiles = true, bool withHiddenFolders = true, bool>.Func fileFilter = null, bool>.Func dirFilter = null ) : void

Recursively copy a directory, creates it if it does not already exists. Throws an IOException, if a same file exists in the target directory.

CreateAndOpenUniqueTimedFile ( string pathPrefix, string fileSuffix, System.DateTime time, FileAccess access, FileShare share, int bufferSize, FileOptions options, int maxTryBeforeGuid = 512 ) : FileStream

Creates and opens a new necessarily unique file in a directory that must exist. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name. You can use FileStream.Name to obtain the file name.

EnsureUniqueTimedFile ( string pathPrefix, string fileSuffix, System.DateTime time, int maxTryBeforeGuid = 512 ) : string

Gets a path to a necessarily unique named file. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name.

FormatTimedUniqueFilePart ( System.DateTime time ) : string

Formats a string that is file name compatible from the given time and a Guid.NewGuid() where time uses FileNameUniqueTimeUtcFormat and the new Guid is encoded with http://en.wikipedia.org/wiki/Base64#URL_applications.

IndexOfInvalidFileNameChars ( string path ) : int

Finds the first character index of any characters that are invalid in a file name. This method (and IndexOfInvalidPathChars) avoid the allocation of the array each time Path.GetInvalidFileNameChars is called.

IndexOfInvalidPathChars ( string path ) : int

Finds the first character index of any characters that are invalid in a path. This method (and IndexOfInvalidFileNameChars) avoid the allocation of the array each time Path.GetInvalidPathChars is called.

MatchFileNameUniqueTimeUtcFormat ( this @this, System.DateTime &time ) : bool

Matches a DateTime in the FileNameUniqueTimeUtcFormat format.

MoveToUniqueTimedFile ( string sourceFilePath, string pathPrefix, string fileSuffix, System.DateTime time, int maxTryBeforeGuid = 512 ) : string

Moves (renames) a file to a necessarily unique named file. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name.

NormalizePathSeparator ( string path, bool ensureTrailingBackslash ) : string

Canonicalizes the path: all '/' and '\' are mapped to Path.DirectorySeparatorChar (and Path.AltDirectorySeparatorChar will also be transformed).

TryParseFileNameUniqueTimeUtcFormat ( string s, System.DateTime &time, bool allowSuffix = false ) : bool

Tries to parse a string formatted with the FileNameUniqueTimeUtcFormat. The string must contain only the time unless allowSuffix is true.

WriteUniqueTimedFile ( string pathPrefix, string fileSuffix, System.DateTime time, byte content, bool withUTF8Bom, int maxTryBeforeGuid = 3 ) : string

Creates a new necessarily unique file and writes bytes content in a directory that must exist. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name.

Private Methods

Method Description
FindUniqueTimedFile ( string pathPrefix, string fileSuffix, System.DateTime time, int maxTryBeforeGuid, bool>.Func tester ) : string
TryCreateFile ( string path ) : bool
TryCreateNew ( string timedPath, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream &f ) : bool
TryMoveTo ( string sourceFilePath, string timedPath ) : bool

Method Details

CheckForWriteAccess() static public method

Waits for a file to be writable or does not exist (if it does not exist, it can be created!). The file is opened and close. Waits the number of nbMaxMilliSecond before leaving and returning false: when 0 (the default), there is no wai. A nbMaxMilliSecond below 20 ~ 30 milliseconds is not accurate: even with nbMaxMilliSecond = 1 this method will return true if the file becomes writable during the next 10 or 20 milliseconds.
static public CheckForWriteAccess ( string path, int nbMaxMilliSecond ) : bool
path string The path of the file to write to.
nbMaxMilliSecond int Maximum number of milliseconds to wait before returning false.
return bool

CompressFileToGzipFile() public static method

Compresses a file to another file, using GZip at the given compression level.
public static CompressFileToGzipFile ( string sourceFilePath, string destinationPath, bool deleteSourceFileOnSuccess, CompressionLevel level = CompressionLevel.Optimal, int bufferSize = 64*1024 ) : void
sourceFilePath string The source file path.
destinationPath string The destination path. If it doesn't exist, it will be created. If it exists, it will be replaced.
deleteSourceFileOnSuccess bool if set to true, will delete source file if no errors occured during compression.
level CompressionLevel Compression level to use.
bufferSize int Size of the buffer, in bytes.
return void

CompressFileToGzipFileAsync() public static method

Compresses a file to another file asynchronously, using GZip at the given compression level.
public static CompressFileToGzipFileAsync ( string sourceFilePath, string destinationPath, CancellationToken cancellationToken = default(CancellationToken), bool deleteSourceFileOnSuccess = true, CompressionLevel level = CompressionLevel.Optimal, int bufferSize = 64*1024 ) : Task
sourceFilePath string The source file path.
destinationPath string The destination path. If it doesn't exist, it will be created. If it exists, it will be replaced.
cancellationToken System.Threading.CancellationToken Optional cancellation token for the task.
deleteSourceFileOnSuccess bool If set to true, will delete source file if no error occurred during compression.
level CompressionLevel Compression level to use.
bufferSize int Size of the buffer, in bytes.
return Task

CopyDirectory() public static method

Recursively copy a directory, creates it if it does not already exists. Throws an IOException, if a same file exists in the target directory.
public static CopyDirectory ( DirectoryInfo src, DirectoryInfo target, bool withHiddenFiles = true, bool withHiddenFolders = true, bool>.Func fileFilter = null, bool>.Func dirFilter = null ) : void
src System.IO.DirectoryInfo The source directory.
target System.IO.DirectoryInfo The target directory.
withHiddenFiles bool False to skip hidden files.
withHiddenFolders bool False to skip hidden folders.
fileFilter bool>.Func Optional predicate for directories.
dirFilter bool>.Func Optional predicate for files.
return void

CreateAndOpenUniqueTimedFile() public static method

Creates and opens a new necessarily unique file in a directory that must exist. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name. You can use FileStream.Name to obtain the file name.
public static CreateAndOpenUniqueTimedFile ( string pathPrefix, string fileSuffix, System.DateTime time, FileAccess access, FileShare share, int bufferSize, FileOptions options, int maxTryBeforeGuid = 512 ) : FileStream
pathPrefix string The path prefix. Must not be null. Must be a valid path and may ends with a prefix for the file name itself.
fileSuffix string Suffix for the file name. Must not be null. Typically an extension (like ".txt").
time System.DateTime The time that will be used to create the file name. It must be an UTC time.
access FileAccess /// A constant that determines how the file can be accessed by the FileStream object. /// It can only be or (when set to a is thrown). /// This sets the CanRead and CanWrite properties of the FileStream object. /// CanSeek is true if path specifies a disk file. ///
share FileShare /// A constant that determines how the file will be shared by processes. ///
bufferSize int /// A positive Int32 value greater than 0 indicating the buffer size. For bufferSize values between one and eight, the actual buffer size is set to eight bytes. ///
options FileOptions Specifies additional file options.
maxTryBeforeGuid int /// Maximum value for short hexadecimal uniquifier before using a base 64 guid suffix. Must greater than 0.
return System.IO.FileStream

EnsureUniqueTimedFile() public static method

Gets a path to a necessarily unique named file. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name.
public static EnsureUniqueTimedFile ( string pathPrefix, string fileSuffix, System.DateTime time, int maxTryBeforeGuid = 512 ) : string
pathPrefix string The path prefix. Must not be null. Must be a valid path and may ends with a prefix for the file name itself.
fileSuffix string Suffix for the file name. Must not be null. Typically an extension (like ".txt").
time System.DateTime The time that will be used to create the file name. It must be an UTC time.
maxTryBeforeGuid int /// Maximum value for short hexadecimal uniquifier before using a base 64 guid suffix. Must greater than 0. ///
return string

FormatTimedUniqueFilePart() public static method

Formats a string that is file name compatible from the given time and a Guid.NewGuid() where time uses FileNameUniqueTimeUtcFormat and the new Guid is encoded with http://en.wikipedia.org/wiki/Base64#URL_applications.
public static FormatTimedUniqueFilePart ( System.DateTime time ) : string
time System.DateTime The date time to use.
return string

IndexOfInvalidFileNameChars() public static method

Finds the first character index of any characters that are invalid in a file name. This method (and IndexOfInvalidPathChars) avoid the allocation of the array each time Path.GetInvalidFileNameChars is called.
public static IndexOfInvalidFileNameChars ( string path ) : int
path string Path to check. Can not be null.
return int

IndexOfInvalidPathChars() public static method

Finds the first character index of any characters that are invalid in a path. This method (and IndexOfInvalidFileNameChars) avoid the allocation of the array each time Path.GetInvalidPathChars is called.
public static IndexOfInvalidPathChars ( string path ) : int
path string Path to check. Can not be null.
return int

MatchFileNameUniqueTimeUtcFormat() public static method

Matches a DateTime in the FileNameUniqueTimeUtcFormat format.
public static MatchFileNameUniqueTimeUtcFormat ( this @this, System.DateTime &time ) : bool
@this this
time System.DateTime Result time on success; otherwise .
return bool

MoveToUniqueTimedFile() public static method

Moves (renames) a file to a necessarily unique named file. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name.
public static MoveToUniqueTimedFile ( string sourceFilePath, string pathPrefix, string fileSuffix, System.DateTime time, int maxTryBeforeGuid = 512 ) : string
sourceFilePath string Path of the file to move.
pathPrefix string The path prefix. Must not be null. Must be a valid path and may ends with a prefix for the file name itself.
fileSuffix string Suffix for the file name. Must not be null. Typically an extension (like ".txt").
time System.DateTime The time that will be used to create the file name. It must be an UTC time.
maxTryBeforeGuid int /// Maximum value for short hexadecimal uniquifier before using a base 64 guid suffix. Must greater than 0. ///
return string

NormalizePathSeparator() static public method

Canonicalizes the path: all '/' and '\' are mapped to Path.DirectorySeparatorChar (and Path.AltDirectorySeparatorChar will also be transformed).
static public NormalizePathSeparator ( string path, bool ensureTrailingBackslash ) : string
path string The path to standardize (must be not be null). It is trimmed and if the path is empty, the empty string is returned.
ensureTrailingBackslash bool /// Ensures that the normalized path will end with a . /// It should be true for path to directories because we consider that a directory path SHOULD end with /// the slash as often as possible. /// When is empty, this is not applied to preserve the fact that the string is empty. ///
return string

TryParseFileNameUniqueTimeUtcFormat() public static method

Tries to parse a string formatted with the FileNameUniqueTimeUtcFormat. The string must contain only the time unless allowSuffix is true.
public static TryParseFileNameUniqueTimeUtcFormat ( string s, System.DateTime &time, bool allowSuffix = false ) : bool
s string The string to parse.
time System.DateTime Result time on success.
allowSuffix bool True to accept a string that starts with the time and contains more text.
return bool

WriteUniqueTimedFile() public static method

Creates a new necessarily unique file and writes bytes content in a directory that must exist. The file name is based on a DateTime, with an eventual uniquifier if a file already exists with the same name.
public static WriteUniqueTimedFile ( string pathPrefix, string fileSuffix, System.DateTime time, byte content, bool withUTF8Bom, int maxTryBeforeGuid = 3 ) : string
pathPrefix string The path prefix. Must not be null. Must be a valid path and may ends with a prefix for the file name itself.
fileSuffix string Suffix for the file name. Must not be null. Typically an extension (like ".txt").
time System.DateTime The time that will be used to create the file name. It should be an UTC time.
content byte The bytes to write. Can be null or empty if the file must only be created.
withUTF8Bom bool True to write the UTF8 Byte Order Mask (the preamble).
maxTryBeforeGuid int Maximum value for short hexa uniquifier before using a base 64 guid suffix. Must between 0 and 15 (included).
return string

Property Details

AltDirectorySeparatorString public static property

Gets the Path.AltDirectorySeparatorChar as a string.
public static string AltDirectorySeparatorString
return string

DirectorySeparatorString public static property

Gets the Path.DirectorySeparatorChar as a string.
public static string DirectorySeparatorString
return string

FileNameUniqueTimeUtcFormat public static property

A display format for DateTime that supports round-trips, is readable and can be used in path or url (the DateTime should be in UTC since DateTime.Kind is ignored). Use MatchFileNameUniqueTimeUtcFormat or TryParseFileNameUniqueTimeUtcFormat to parse it (it uses the correct DateTimeStyles). It is: @"yyyy-MM-dd HH\hmm.ss.fffffff"
public static string FileNameUniqueTimeUtcFormat
return string

GzipFileHeader static public property

The file header for gzipped files.
static public byte[] GzipFileHeader
return byte[]

InexistingFile static public property

Combination of FileAttributes that can not exist: it can be used to tag non existing files among other existing (i.e. valid) file attributes.
static public FileAttributes InexistingFile
return FileAttributes

MissingFileLastWriteTimeUtc public static property

The time returned by File.GetLastWriteTimeUtc when the file does not exist. From MSDN: If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).
public static DateTime,System MissingFileLastWriteTimeUtc
return System.DateTime