Class FileUtils
Provides filesystem-related helper methods.
public static class FileUtils
- Inheritance
-
objectFileUtils
Methods
AreHardlinked(string, string)
Determines whether two files are hardlinked.
public static bool AreHardlinked(string path1, string path2)
Parameters
Returns
Exceptions
- IOException
There was an IO problem checking the files.
- UnauthorizedAccessException
You have insufficient rights to check the files.
CanonicalizeAcl(ObjectSecurity)
Fixes ACLs that are not canonical (not ordered correctly).
public static void CanonicalizeAcl(this ObjectSecurity objectSecurity)
Parameters
objectSecurityObjectSecurity
Create(string, long)
Creates or replaces a file. Pre-allocates the expected size of the file if possible.
public static FileStream Create(string path, long expectedSize)
Parameters
pathstringThe path of the file.
expectedSizelongThe initial allocation size in bytes for the file.
Returns
- FileStream
A stream for writing the file. No read access.
CreateDirectoryLink(string, string)
Creates a new link to a directory. Uses a symbolic link where possible and falls back to an NTFS junction on Windows if the privileges for creating symbolic links are missing.
public static void CreateDirectoryLink(string sourcePath, string targetPath)
Parameters
sourcePathstringThe path of the link to create.
targetPathstringThe path of the directory to point to (relative to
sourcePath). Junctions store this as an absolute path.
Exceptions
- IOException
Creating the link failed.
- NotAdminException
You lack the privilege for creating symbolic links and
targetPathcannot be reached by a junction (e.g., a network path).- UnauthorizedAccessException
You have insufficient rights to create the link.
- PlatformNotSupportedException
This method is called on a system with no directory link support.
CreateHardlink(string, string)
Creates a new hard link between two files.
public static void CreateHardlink(string sourcePath, string targetPath)
Parameters
sourcePathstringThe path of the link to create.
targetPathstringThe absolute path of the existing file to point to.
Exceptions
- IOException
Creating the hard link failed.
- UnauthorizedAccessException
You have insufficient rights to create the hard link.
- PlatformNotSupportedException
This method is called on a system with no hard link support.
CreateSymlink(string, string)
Creates a new symbolic link to a file or directory.
public static void CreateSymlink(string sourcePath, string targetPath)
Parameters
sourcePathstringThe path of the link to create.
targetPathstringThe path of the existing file or directory to point to (relative to
sourcePath).
Exceptions
- IOException
Creating the symbolic link failed.
- NotAdminException
You lack the privilege for creating symbolic links.
- UnauthorizedAccessException
You have insufficient rights to create the symbolic link.
- PlatformNotSupportedException
This method is called on a system with no symbolic link support.
DetectNameAliasing(string)
Determines how the filesystem underlying a specific directory resolves names by creating a uniquely named temporary file in it.
public static NameAliasing DetectNameAliasing(string path)
Parameters
pathstringThe path of the directory to check. Settings like Linux casefolding can differ between directories on the same volume, so check the actual directory rather than the volume root.
Returns
Exceptions
- DirectoryNotFoundException
The specified directory doesn't exist.
- IOException
Writing to the directory fails.
- UnauthorizedAccessException
You have insufficient rights to write to the directory.
DetermineTimeAccuracy(string)
Determines the accuracy with which the filesystem underlying a specific directory can store file-changed times.
public static int DetermineTimeAccuracy(string path)
Parameters
pathstringThe path of the directory to check.
Returns
- int
The accuracy in number of seconds. (i.e. 0 = perfect, 1 = may be off by up to one second)
Exceptions
- DirectoryNotFoundException
The specified directory doesn't exist.
- IOException
Writing to the directory fails.
- UnauthorizedAccessException
You have insufficient rights to write to the directory.
DisableWriteProtection(string)
Removes whatever means the current platform provides to prevent write access to a directory (read-only attribute, ACLs, Unix octals, etc.).
public static void DisableWriteProtection(string path)
Parameters
pathstringThe directory to unprotect.
Remarks
May do nothing if the platform doesn't provide any known protection mechanisms.
Exceptions
- IOException
There was a problem removing the write protection.
- UnauthorizedAccessException
You have insufficient rights to remove the write protection.
EnableWriteProtection(string)
Uses the best means the current platform provides to prevent further write access to a directory (read-only attribute, ACLs, Unix octals, etc.).
public static void EnableWriteProtection(string path)
Parameters
pathstringThe directory to protect.
Remarks
May do nothing if the platform doesn't provide any known protection mechanisms.
Exceptions
- IOException
There was a problem applying the write protection.
- UnauthorizedAccessException
You have insufficient rights to apply the write protection.
ExistsCaseSensitive(string)
Like Exists(string) but case-sensitive, even on Windows.
public static bool ExistsCaseSensitive(string path)
Parameters
pathstring
Returns
GetFileID(FileInfo)
Returns the file ID (on Windows) or Inode (on Unix) of a file.
public static long GetFileID(this FileInfo file)
Parameters
fileFileInfoThe file.
Returns
Exceptions
- IOException
There was an IO problem checking the files.
- UnauthorizedAccessException
You have insufficient rights to check the files.
GetFileID(string)
Returns the file ID (on Windows) or Inode (on Unix) of a file.
public static long GetFileID(string path)
Parameters
pathstringThe path of the file.
Returns
Exceptions
- IOException
There was an IO problem checking the file.
- UnauthorizedAccessException
You have insufficient rights to check the files.
GetFilesRecursive(string, bool)
Returns the full paths of all files in a directory and its subdirectories.
public static IList<string> GetFilesRecursive(string path, bool followDirSymlinks = false)
Parameters
pathstringThe path of the directory to search for files.
followDirSymlinksboolIf
truerecurse into directory symlinks.
Returns
IsBreakoutPath(string?)
Determines whether a path might escape its parent directory (by being absolute or using ..).
public static bool IsBreakoutPath(string? path)
Parameters
pathstring
Returns
IsDirectoryLink(DirectoryInfo)
Checks whether a directory is a link to another directory, i.e., a symbolic link or an NTFS junction.
public static bool IsDirectoryLink(this DirectoryInfo directory)
Parameters
directoryDirectoryInfoThe directory to check.
Returns
- bool
trueifdirectoryis a symbolic link or junction;falseotherwise.
Remarks
Use IsSymlink(string) instead if you need to distinguish symbolic links from junctions, e.g., to recreate them.
Exceptions
- IOException
There was an IO problem reading the directory.
- UnauthorizedAccessException
Read access to the directory was denied.
IsExecutable(string)
Checks whether a file is marked as Unix-executable.
public static bool IsExecutable(string path)
Parameters
pathstring
Returns
- bool
trueifpathpoints to an executable;falseotherwise.
Remarks
Will return false for non-existing files. Will always return false on non-Unixoid systems.
Exceptions
- UnauthorizedAccessException
You have insufficient rights to query the file's properties.
IsRegularFile(string)
Checks whether a file is a regular file (i.e. not a device file, symbolic link, etc.).
public static bool IsRegularFile(string path)
Parameters
pathstring
Returns
- bool
trueifpathpoints to a regular file;falseotherwise.
Remarks
Will return false for non-existing files.
Exceptions
- UnauthorizedAccessException
You have insufficient rights to query the file's properties.
IsSymlink(FileSystemInfo, out string)
Checks whether a file is a Unix symbolic link.
public static bool IsSymlink(this FileSystemInfo item, out string target)
Parameters
itemFileSystemInfoThe file to check.
targetstringReturns the target the symbolic link points to if it exists.
Returns
- bool
trueifitempoints to a symbolic link;falseotherwise.
Exceptions
- IOException
There was an IO problem reading the file.
- UnauthorizedAccessException
Read access to the file was denied.
IsSymlink(string)
Checks whether a file is a symbolic link.
public static bool IsSymlink(string path)
Parameters
pathstringThe path of the file to check.
Returns
- bool
trueifpathpoints to a symbolic link;falseotherwise.
Exceptions
- IOException
There was an IO problem reading the file.
- UnauthorizedAccessException
Read access to the file was denied.
IsSymlink(string, out string)
Checks whether a file is a symbolic link.
public static bool IsSymlink(string path, out string target)
Parameters
pathstringThe path of the file to check.
targetstringReturns the target the symbolic link points to if it exists.
Returns
- bool
trueifpathpoints to a symbolic link;falseotherwise.
Exceptions
- IOException
There was an IO problem reading the file.
- UnauthorizedAccessException
Read access to the file was denied.
IsUnixFS(string)
Checks whether a directory is located on a filesystem with support for Unixoid features such as executable bits.
public static bool IsUnixFS(string path)
Parameters
pathstring
Returns
- bool
trueifpathpoints to directory on a Unixoid filesystem;falseotherwise.
Remarks
Will always return false on non-Unixoid systems.
May create a temporary file in the directory to probe for executable bit support. Assumes a Unixoid filesystem if this fails.
Exceptions
- DirectoryNotFoundException
The specified directory doesn't exist.
- IOException
Checking the directory failed.
- UnauthorizedAccessException
You have insufficient right to stat to the directory.
PathEquals(string?, string?)
Determines whether two file-system paths point to the same location.
public static bool PathEquals(string? path1, string? path2)
Parameters
Returns
Remarks
Applies path normalization. Does not resolve symlinks. Case-insensitive on Windows and macOS.
ReadExtendedMetadata(string, string)
Reads metadata from an NTFS Alternate Data Stream (Windows) or extended file attribute (Unixoid).
public static byte[]? ReadExtendedMetadata(string path, string name)
Parameters
pathstringThe path of the file the Alternate Data Stream is associated with.
namestringThe name of the metadata stream.
Returns
- byte[]
The contents of the metadata stream;
nullif the file exists but the stream specified bynamedoes not.
Exceptions
- FileNotFoundException
The file specified by
pathdoes not exist.- IOException
There was a problem reading the metadata stream.
- PlatformNotSupportedException
The current operating system provides no method for storing extended metadata.
ReadFirstLine(FileInfo, Encoding)
Reads the first line of text from a file.
public static string? ReadFirstLine(this FileInfo file, Encoding encoding)
Parameters
Returns
- string
The first line of text in the file;
nullif the file is empty.
Exceptions
- IOException
A problem occurred while reading the file.
- UnauthorizedAccessException
Read access to the file is not permitted.
RelativeTo(FileSystemInfo, FileSystemInfo)
Returns a relative path pointing to target from baseRef.
public static string RelativeTo(this FileSystemInfo target, FileSystemInfo baseRef)
Parameters
targetFileSystemInfobaseRefFileSystemInfo
Returns
Replace(string, string)
Replaces one file with another. Rolls back in case of problems. If the destination file does not exist yet, this acts like a simple rename.
public static void Replace(string sourcePath, string destinationPath)
Parameters
sourcePathstringThe path of source directory.
destinationPathstringThe path of the target directory. Must reside on the same filesystem as
sourcePath.
Exceptions
- ArgumentException
sourcePathanddestinationPathare equal.- IOException
The file could not be replaced.
- UnauthorizedAccessException
The read or write access to one of the files was denied.
ResetAcl(DirectoryInfo)
Removes any custom ACLs a user may have set, restores ACL inheritance and sets the Administrators group as the owner.
public static void ResetAcl(this DirectoryInfo directory)
Parameters
directoryDirectoryInfo
SetExecutable(string, bool)
Marks a file as Unix-executable or not Unix-executable. Only works on Unixoid systems!
public static void SetExecutable(string path, bool executable)
Parameters
pathstringThe file to mark as executable or not executable.
executablebooltrueto mark the file as executable,falseto mark it as not executable.
Exceptions
- FileNotFoundException
pathpoints to a file that does not exist or cannot be accessed.- UnauthorizedAccessException
You have insufficient rights to change the file's properties.
- PlatformNotSupportedException
This method is called on a non-Unixoid system.
ToNativePath(string?)
Replaces Unix-style directory slashes with DirectorySeparatorChar.
public static string? ToNativePath(this string? value)
Parameters
valuestring
Returns
ToUnixPath(string?)
Replaces DirectorySeparatorChar with Unix-style directory slashes.
public static string? ToUnixPath(this string? value)
Parameters
valuestring
Returns
Touch(string)
Sets the "last modified" timestamp for a file to now. Creates a new empty file if it does not exist yet.
public static void Touch(string path)
Parameters
pathstring
Exceptions
- IOException
Creating the file or updating its timestamp failed.
- UnauthorizedAccessException
You have insufficient rights to create the file or update its timestamp.
Walk(FileSystemInfo, Action<DirectoryInfo>?, Action<FileInfo>?, bool)
Walks a directory structure recursively and performs an action for every directory and file encountered.
public static void Walk(this FileSystemInfo element, Action<DirectoryInfo>? dirAction = null, Action<FileInfo>? fileAction = null, bool followDirSymlinks = false)
Parameters
elementFileSystemInfoThe directory (or single file) to walk.
dirActionAction<DirectoryInfo>The action to perform for every found directory (including the starting
element); can benull.fileActionAction<FileInfo>The action to perform for every found file; can be
null.followDirSymlinksboolIf
truerecurse into directory symlinks or junctions; iffalseonly executedirActionfor them but do not recurse.
WalkThroughPrefix(DirectoryInfo)
Skips through any directories that only contain a single subdirectory and no files.
public static DirectoryInfo WalkThroughPrefix(this DirectoryInfo directory)
Parameters
directoryDirectoryInfo
Returns
Remarks
Ignores files that start with a dot.
WriteExtendedMetadata(string, string, byte[])
Writes metadata to an NTFS Alternate Data Stream (Windows) or extended file attribute (Unixoid).
public static void WriteExtendedMetadata(string path, string name, byte[] data)
Parameters
pathstringThe path of the file to associate the metadata with.
namestringThe name of the metadata stream.
databyte[]The data to write to the metadata stream.
Exceptions
- FileNotFoundException
The file specified by
pathdoes not exist.- IOException
There was a problem writing the metadata stream.
- UnauthorizedAccessException
You have insufficient rights to write the metadata.
- PlatformNotSupportedException
The current operating system provides no method for storing extended metadata.