Class IOHelper
Provides helper methods for file and directory operations.
public static class IOHelper
- Inheritance
-
IOHelper
- Inherited Members
Fields
DocsVar
The %Documents% variable.
public const string DocsVar = "%Documents%"
Field Value
Methods
AddRelative(string, string)
Adds a relative segment to the current path and returns the fully qualified path.
public static string AddRelative(this string path, string relativePart)
Parameters
Returns
- string
The combined full path.
BlockDeleteDir(string, bool, int, int)
Deletes a directory in a blocking manner.
public static bool BlockDeleteDir(string dir, bool isRecursive = false, int iterCount = 1000, int sleep = 0)
Parameters
dir
stringThe directory to delete.
isRecursive
boolIndicates whether to delete subdirectories recursively.
iterCount
intNumber of iterations to attempt deletion.
sleep
intSleep duration between attempts in milliseconds.
Returns
- bool
True if the directory still exists after deletion attempts; otherwise, false.
CheckDirContainFiles(string)
Checks whether the directory contains files or subdirectories that contain files.
public static bool CheckDirContainFiles(string path)
Parameters
path
stringThe directory path to check.
Returns
- bool
True if the directory contains any files; otherwise, false.
CheckDirContainsAnything(string)
Checks whether the directory contains any files or subdirectories.
public static bool CheckDirContainsAnything(string path)
Parameters
path
stringThe directory path to check.
Returns
- bool
True if the directory contains any entries; otherwise, false.
CheckInstallation(string)
Checks if the specified installation directory exists and contains files or subdirectories.
public static bool CheckInstallation(string path)
Parameters
path
stringThe installation directory path.
Returns
- bool
True if the installation is valid; otherwise, false.
ClearDirectory(string, Func<string, bool>)
Clears the specified directory by deleting its files and subdirectories.
public static DirectoryInfo ClearDirectory(string path, Func<string, bool> filter = null)
Parameters
path
stringThe directory path to clear.
filter
Func<string, bool>Optional filter to determine which files to delete.
Returns
- DirectoryInfo
A DirectoryInfo for the cleared directory.
ClearDirectoryAsync(string, Func<string, bool>, CancellationToken)
Asynchronously clears the specified directory by deleting its files and subdirectories.
public static Task<DirectoryInfo> ClearDirectoryAsync(string path, Func<string, bool> filter = null, CancellationToken cancellationToken = default)
Parameters
path
stringThe directory path to clear.
filter
Func<string, bool>Optional filter to determine which files to delete.
cancellationToken
CancellationTokenA cancellation token.
Returns
- Task<DirectoryInfo>
A task that represents the asynchronous operation, containing a DirectoryInfo for the cleared directory.
CopyAndMakeWritable(string, string)
Copies a file to the specified destination and makes the copy writable.
public static string CopyAndMakeWritable(string fileName, string destPath)
Parameters
Returns
- string
The destination file path.
CopyDirectory(string, string)
Copies the content of one directory to another.
public static void CopyDirectory(string sourcePath, string destPath)
Parameters
CopyDirectoryAsync(string, string, CancellationToken)
Asynchronously copies the content of one directory to another.
public static Task CopyDirectoryAsync(string sourcePath, string destPath, CancellationToken cancellationToken = default)
Parameters
sourcePath
stringThe source directory path.
destPath
stringThe destination directory path.
cancellationToken
CancellationTokenA cancellation token.
Returns
- Task
A task that represents the asynchronous operation.
CopySync(Stream, Stream, int)
Copies a specified number of bytes synchronously from the source stream to the destination stream.
public static void CopySync(this Stream source, Stream destination, int count)
Parameters
source
StreamThe source stream to copy from.
destination
StreamThe destination stream to copy to.
count
intThe number of bytes to copy.
CreateDirIfNotExists(string)
Creates the directory for the specified file if it does not already exist.
public static bool CreateDirIfNotExists(this string fullPath)
Parameters
fullPath
stringThe full path to the file.
Returns
- bool
True if the directory was created; otherwise, false.
CreateFile(string, string, string, byte[])
Creates a file with the specified content.
public static void CreateFile(string rootPath, string relativePath, string fileName, byte[] content)
Parameters
rootPath
stringThe root path.
relativePath
stringThe relative path to the file.
fileName
stringThe file name.
content
byte[]The content as a byte array.
CreateTempDir()
Creates a temporary directory and returns its path.
public static string CreateTempDir()
Returns
- string
The path to the new temporary directory.
DeleteEmptyDirs(string)
Recursively deletes empty directories starting from the specified directory.
public static void DeleteEmptyDirs(string dir)
Parameters
dir
stringThe root directory to check and delete if empty.
EnumerateLines(Stream, Encoding, bool)
Enumerates the lines in the stream using the specified encoding.
public static IEnumerable<string> EnumerateLines(this Stream stream, Encoding encoding = null, bool leaveOpen = true)
Parameters
stream
StreamThe stream to read lines from.
encoding
EncodingThe encoding to use when reading the stream. Defaults to UTF8 if null.
leaveOpen
boolIndicates whether to leave the stream open after reading.
Returns
- IEnumerable<string>
An enumerable collection of strings, each representing a line from the stream.
Execute(string, string, Action<string>, Action<string>, Action<ProcessStartInfo>, TimeSpan, string, ProcessPriorityClass?)
Executes a process with specified arguments and output handlers.
public static int Execute(string fileName, string arg, Action<string> output, Action<string> error, Action<ProcessStartInfo> infoHandler = null, TimeSpan waitForExit = default, string stdInput = null, ProcessPriorityClass? priority = null)
Parameters
fileName
stringThe process file name.
arg
stringArguments for the process.
output
Action<string>Action to handle standard output.
error
Action<string>Action to handle standard error.
infoHandler
Action<ProcessStartInfo>Optional action to modify process start info.
waitForExit
TimeSpanTimeSpan to wait for process exit.
stdInput
stringStandard input to write to the process.
priority
ProcessPriorityClass?Optional process priority.
Returns
- int
The process exit code.
ExecuteAsync(string, string, Action<string>, Action<string>, Action<ProcessStartInfo>, string, ProcessPriorityClass?, CancellationToken)
Asynchronously executes a process with specified arguments and output handlers.
public static Task<int> ExecuteAsync(string fileName, string arg, Action<string> output, Action<string> error, Action<ProcessStartInfo> infoHandler = null, string stdInput = null, ProcessPriorityClass? priority = null, CancellationToken cancellationToken = default)
Parameters
fileName
stringThe file name to execute.
arg
stringArguments for the process.
output
Action<string>Action to handle standard output.
error
Action<string>Action to handle standard error.
infoHandler
Action<ProcessStartInfo>Optional action to modify process start info.
stdInput
stringStandard input to send to the process.
priority
ProcessPriorityClass?Optional process priority.
cancellationToken
CancellationTokenA cancellation token.
Returns
GetActualBuffer(MemoryStream)
Gets the actual buffer of the MemoryStream that contains the written data.
public static ArraySegment<byte> GetActualBuffer(this MemoryStream stream)
Parameters
stream
MemoryStreamThe MemoryStream to retrieve the buffer from.
Returns
- ArraySegment<byte>
An ArraySegment containing the actual data from the MemoryStream.
GetDirectories(string, string, SearchOption)
Retrieves the directories within the specified path matching the search pattern.
public static IEnumerable<string> GetDirectories(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
Parameters
path
stringThe root directory to search.
searchPattern
stringThe search pattern.
searchOption
SearchOptionSearch option to determine whether to search subdirectories.
Returns
- IEnumerable<string>
An enumerable of matching directory paths.
GetDiskFreeSpace(string)
Gets the available free space on the specified drive.
public static long GetDiskFreeSpace(string driveName)
Parameters
driveName
stringThe drive name (e.g., "C:").
Returns
- long
The amount of free space in bytes.
GetRelativePath(string, string)
Gets the relative path from a folder to a file.
public static string GetRelativePath(this string fileFull, string folder)
Parameters
Returns
- string
The relative file path.
GetTimestamp(Assembly)
Gets the timestamp of the specified assembly.
public static DateTime GetTimestamp(this Assembly assembly)
Parameters
assembly
AssemblyThe assembly.
Returns
- DateTime
The timestamp when the assembly was built.
GetTimestamp(string)
Gets the timestamp of the specified file.
public static DateTime GetTimestamp(string filePath)
Parameters
filePath
stringThe file path.
Returns
- DateTime
The timestamp representing when the file was built.
IsDirectory(string)
Determines whether the specified path represents a directory.
public static bool IsDirectory(this string path)
Parameters
path
stringThe file or directory path.
Returns
- bool
True if the path is a directory; otherwise, false.
IsFileLocked(string)
Determines whether the file specified by the path is locked by another process.
public static bool IsFileLocked(string path)
Parameters
path
stringThe path to the file to check.
Returns
- bool
True if the file is locked; otherwise, false.
IsPathIsDir(string)
Determines if the specified path refers to a directory.
public static bool IsPathIsDir(this string path)
Parameters
path
stringThe path to check.
Returns
- bool
True if the path is a directory; otherwise, false.
IsPathsEqual(string, string)
Compares two file paths for equality after normalization.
public static bool IsPathsEqual(string path1, string path2)
Parameters
Returns
- bool
True if both paths are equal; otherwise, false.
NormalizePath(string, CultureInfo)
Normalizes the provided file path for comparison purposes and converts it to lowercase based on the specified culture.
public static string NormalizePath(this string path, CultureInfo culture = null)
Parameters
path
stringThe file path to normalize.
culture
CultureInfoThe culture info to use for lowercasing. Defaults to InstalledUICulture if null.
Returns
- string
The normalized and lowercased file path.
NormalizePathNoLowercase(string)
Normalizes the provided file path for comparison purposes without converting to lowercase.
public static string NormalizePathNoLowercase(this string path)
Parameters
path
stringThe file path to normalize.
Returns
- string
The normalized file path, or null if the input is empty or whitespace.
OpenLink(string, bool)
Opens the specified URL or file path using the default system launcher.
public static bool OpenLink(this string url, bool raiseError)
Parameters
url
stringThe URL or file path to open.
raiseError
boolDetermines if an exception should be raised if opening fails.
Returns
- bool
True if the operation is successful; otherwise, false.
Read(Stream, Type)
Reads an object of the specified type from the stream.
public static object Read(this Stream stream, Type type)
Parameters
Returns
- object
The object read from the stream.
Read(Stream, Type, int)
Reads an object of the specified type from the stream using the provided size.
public static object Read(this Stream stream, Type type, int size)
Parameters
stream
StreamThe stream to read from.
type
TypeThe type of object to read.
size
intThe size in bytes to read.
Returns
- object
The object read from the stream.
ReadBuffer(Stream, int)
Reads exactly the specified number of bytes from the stream into a byte array.
public static byte[] ReadBuffer(this Stream stream, int size)
Parameters
Returns
- byte[]
A byte array containing the data read from the stream.
ReadByteEx(Stream, byte[])
Reads a single byte from a stream.
public static byte ReadByteEx(this Stream stream, byte[] buffer)
Parameters
Returns
- byte
The byte read from the stream.
ReadBytes(Stream, byte[], int, int)
Reads a specified number of bytes from a stream.
public static byte[] ReadBytes(this Stream stream, byte[] buffer, int len, int pos = 0)
Parameters
stream
StreamThe input stream.
buffer
byte[]The buffer to fill.
len
intThe number of bytes to read.
pos
intThe position in the buffer to start filling.
Returns
- byte[]
The buffer containing the read bytes.
ReadInt(Stream, byte[], bool)
Reads an integer value from a stream with specified endianness.
public static int ReadInt(this Stream stream, byte[] buffer, bool isLittleEndian)
Parameters
stream
StreamThe input stream.
buffer
byte[]The buffer used for reading.
isLittleEndian
boolIndicates if the value is in little-endian format.
Returns
- int
The integer value read.
ReadLong(Stream, byte[], bool, int)
Reads a long value from a stream with specified endianness.
public static long ReadLong(this Stream stream, byte[] buffer, bool isLittleEndian, int len = 8)
Parameters
stream
StreamThe input stream.
buffer
byte[]The buffer used for reading.
isLittleEndian
boolIndicates if the value is in little-endian format.
len
intThe length in bytes to read (default is 8).
Returns
- long
The long value read.
ReadShort(Stream, byte[], bool)
Reads a short value from a stream with specified endianness.
public static short ReadShort(this Stream stream, byte[] buffer, bool isLittleEndian)
Parameters
stream
StreamThe input stream.
buffer
byte[]The buffer used for reading.
isLittleEndian
boolIndicates if the value is in little-endian format.
Returns
- short
The short value read.
ReadUInt(Stream, byte[], bool)
Reads an unsigned integer value from a stream with specified endianness.
[CLSCompliant(false)]
public static uint ReadUInt(this Stream stream, byte[] buffer, bool isLittleEndian)
Parameters
stream
StreamThe input stream.
buffer
byte[]The buffer used for reading.
isLittleEndian
boolIndicates if the value is in little-endian format.
Returns
- uint
The unsigned integer value read.
ReadULong(Stream, byte[], bool, int)
Reads an unsigned long value from a stream with specified endianness.
[CLSCompliant(false)]
public static ulong ReadULong(this Stream stream, byte[] buffer, bool isLittleEndian, int len = 8)
Parameters
stream
StreamThe input stream.
buffer
byte[]The buffer used for reading.
isLittleEndian
boolIndicates if the value is in little-endian format.
len
intThe length in bytes to read (default is 8).
Returns
- ulong
The unsigned long value read.
ReadUShort(Stream, byte[], bool)
Reads an unsigned short value from a stream with specified endianness.
[CLSCompliant(false)]
public static ushort ReadUShort(this Stream stream, byte[] buffer, bool isLittleEndian)
Parameters
stream
StreamThe input stream.
buffer
byte[]The buffer used for reading.
isLittleEndian
boolIndicates if the value is in little-endian format.
Returns
- ushort
The unsigned short value read.
Read<T>(Stream)
Reads an object of type T from the stream.
public static T Read<T>(this Stream stream)
Parameters
stream
StreamThe stream to read from.
Returns
- T
The object read from the stream.
Type Parameters
T
The type of object to read.
SafeDeleteDir(string)
Safely deletes a directory.
public static void SafeDeleteDir(this string path)
Parameters
path
stringThe directory path.
Save(byte[], string)
Saves the byte array to a file specified by fileName.
public static byte[] Save(this byte[] data, string fileName)
Parameters
Returns
- byte[]
The original byte array.
Save(Stream, string)
Saves the content of the stream to a file specified by fileName.
public static Stream Save(this Stream stream, string fileName)
Parameters
stream
StreamThe stream whose contents to save.
fileName
stringThe file path to save the stream's contents to.
Returns
- Stream
The original stream.
SizeOf(Type)
Returns the size in bytes of the specified unmanaged type.
public static int SizeOf(this Type type)
Parameters
type
TypeThe type whose size is to be computed.
Returns
- int
The size in bytes of the specified type.
SizeOf<T>()
Returns the size in bytes of an unmanaged type T.
public static int SizeOf<T>()
Returns
- int
The size in bytes of the specified type.
Type Parameters
T
The unmanaged type.
ToFullPath(string)
Converts a relative or partial path to a fully qualified path.
public static string ToFullPath(this string path)
Parameters
path
stringThe input path.
Returns
- string
The absolute path.
ToFullPathIfNeed(string)
Replaces the %Documents% variable in the path with the actual Documents folder path.
public static string ToFullPathIfNeed(this string path)
Parameters
path
stringThe path containing the %Documents% variable.
Returns
- string
The fully qualified path with the Documents folder.
ToHumanReadableFileSize(long)
Converts a byte count to a human-readable file size string.
public static string ToHumanReadableFileSize(this long byteCount)
Parameters
byteCount
longThe number of bytes.
Returns
- string
A formatted string representing the file size.
Truncate(StreamWriter)
Truncates the underlying stream used by the StreamWriter by clearing its content.
public static void Truncate(this StreamWriter writer)
Parameters
writer
StreamWriterThe StreamWriter whose stream is to be truncated.
TrySave(byte[], string, Action<Exception>)
Attempts to save the byte array to a file and handles any exceptions using the provided errorHandler.
public static bool TrySave(this byte[] data, string fileName, Action<Exception> errorHandler)
Parameters
data
byte[]The byte array to save.
fileName
stringThe file path to save the data to.
errorHandler
Action<Exception>The action to handle exceptions.
Returns
- bool
True if the save operation was successful; otherwise, false.
WriteByteEx(Stream, byte[], byte)
Writes a single byte to a stream.
public static void WriteByteEx(this Stream stream, byte[] buffer, byte value)
Parameters
stream
StreamThe output stream.
buffer
byte[]The buffer used for writing.
value
byteThe byte value to write.
WriteBytes(Stream, byte[], int, int)
Writes the specified bytes to a stream.
public static void WriteBytes(this Stream stream, byte[] bytes, int len, int pos = 0)
Parameters
stream
StreamThe output stream.
bytes
byte[]The byte array.
len
intThe number of bytes to write.
pos
intThe position in the array to start writing from.
WriteEx(Stream, object)
Writes an extended representation of the provided object to the stream, prefixing its length.
public static void WriteEx(this Stream stream, object value)
Parameters
WriteInt(Stream, byte[], int, bool)
Writes an integer value to a stream with specified endianness.
public static void WriteInt(this Stream stream, byte[] buffer, int value, bool isLittleEndian)
Parameters
stream
StreamThe output stream.
buffer
byte[]The buffer used for writing.
value
intThe integer value to write.
isLittleEndian
boolIndicates if the value is in little-endian format.
WriteLong(Stream, byte[], long, bool, int)
Writes a long value to a stream with specified endianness.
public static void WriteLong(this Stream stream, byte[] buffer, long value, bool isLittleEndian, int len = 8)
Parameters
stream
StreamThe output stream.
buffer
byte[]The buffer used for writing.
value
longThe long value to write.
isLittleEndian
boolIndicates if the value is in little-endian format.
len
intThe length in bytes to write (default is 8).
WriteRaw(Stream, byte[])
Writes a raw byte array to the stream.
public static void WriteRaw(this Stream stream, byte[] buffer)
Parameters
WriteRaw(Stream, object)
Writes the raw byte representation of the provided object to the stream.
public static void WriteRaw(this Stream stream, object value)
Parameters
stream
StreamThe stream to write to.
value
objectThe object to write. Its byte representation will be determined.
WriteShort(Stream, byte[], short, bool)
Writes a short value to a stream with specified endianness.
public static void WriteShort(this Stream stream, byte[] buffer, short value, bool isLittleEndian)
Parameters
stream
StreamThe output stream.
buffer
byte[]The buffer used for writing.
value
shortThe short value to write.
isLittleEndian
boolIndicates if the value is in little-endian format.
WriteUInt(Stream, byte[], uint, bool)
Writes an unsigned integer value to a stream with specified endianness.
[CLSCompliant(false)]
public static void WriteUInt(this Stream stream, byte[] buffer, uint value, bool isLittleEndian)
Parameters
stream
StreamThe output stream.
buffer
byte[]The buffer used for writing.
value
uintThe unsigned integer value to write.
isLittleEndian
boolIndicates if the value is in little-endian format.
WriteULong(Stream, byte[], ulong, bool, int)
Writes an unsigned long value to a stream with specified endianness.
[CLSCompliant(false)]
public static void WriteULong(this Stream stream, byte[] buffer, ulong value, bool isLittleEndian, int len = 8)
Parameters
stream
StreamThe output stream.
buffer
byte[]The buffer used for writing.
value
ulongThe unsigned long value to write.
isLittleEndian
boolIndicates if the value is in little-endian format.
len
intThe length in bytes to write (default is 8).
WriteUShort(Stream, byte[], ushort, bool)
Writes an unsigned short value to a stream with specified endianness.
[CLSCompliant(false)]
public static void WriteUShort(this Stream stream, byte[] buffer, ushort value, bool isLittleEndian)