Table of Contents

Class IOHelper

Namespace
Ecng.Common
Assembly
Ecng.Common.dll

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

string

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

path string

The base path.

relativePart string

The relative segment to add.

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 string

The directory to delete.

isRecursive bool

Indicates whether to delete subdirectories recursively.

iterCount int

Number of iterations to attempt deletion.

sleep int

Sleep 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 string

The 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 string

The 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 string

The 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 string

The 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 string

The directory path to clear.

filter Func<string, bool>

Optional filter to determine which files to delete.

cancellationToken CancellationToken

A 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

fileName string

The source file path.

destPath string

The destination directory path.

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

sourcePath string

The source directory path.

destPath string

The destination directory path.

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 string

The source directory path.

destPath string

The destination directory path.

cancellationToken CancellationToken

A 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 Stream

The source stream to copy from.

destination Stream

The destination stream to copy to.

count int

The 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 string

The 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 string

The root path.

relativePath string

The relative path to the file.

fileName string

The 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 string

The 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 Stream

The stream to read lines from.

encoding Encoding

The encoding to use when reading the stream. Defaults to UTF8 if null.

leaveOpen bool

Indicates 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 string

The process file name.

arg string

Arguments 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 TimeSpan

TimeSpan to wait for process exit.

stdInput string

Standard 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 string

The file name to execute.

arg string

Arguments 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 string

Standard input to send to the process.

priority ProcessPriorityClass?

Optional process priority.

cancellationToken CancellationToken

A cancellation token.

Returns

Task<int>

A task that represents the asynchronous operation, containing the process exit code.

GetActualBuffer(MemoryStream)

Gets the actual buffer of the MemoryStream that contains the written data.

public static ArraySegment<byte> GetActualBuffer(this MemoryStream stream)

Parameters

stream MemoryStream

The 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 string

The root directory to search.

searchPattern string

The search pattern.

searchOption SearchOption

Search 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 string

The 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

fileFull string

The full file path.

folder string

The base folder.

Returns

string

The relative file path.

GetTimestamp(Assembly)

Gets the timestamp of the specified assembly.

public static DateTime GetTimestamp(this Assembly assembly)

Parameters

assembly Assembly

The 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 string

The 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 string

The 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 string

The 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 string

The 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

path1 string

The first file path to compare.

path2 string

The second file path to compare.

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 string

The file path to normalize.

culture CultureInfo

The 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 string

The file path to normalize.

Returns

string

The normalized file path, or null if the input is empty or whitespace.

Opens the specified URL or file path using the default system launcher.

public static bool OpenLink(this string url, bool raiseError)

Parameters

url string

The URL or file path to open.

raiseError bool

Determines 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

stream Stream

The stream to read from.

type Type

The type of object to read.

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 Stream

The stream to read from.

type Type

The type of object to read.

size int

The 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

stream Stream

The stream to read from.

size int

The number of bytes to read.

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

stream Stream

The input stream.

buffer byte[]

The buffer used for reading.

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 Stream

The input stream.

buffer byte[]

The buffer to fill.

len int

The number of bytes to read.

pos int

The 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 Stream

The input stream.

buffer byte[]

The buffer used for reading.

isLittleEndian bool

Indicates 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 Stream

The input stream.

buffer byte[]

The buffer used for reading.

isLittleEndian bool

Indicates if the value is in little-endian format.

len int

The 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 Stream

The input stream.

buffer byte[]

The buffer used for reading.

isLittleEndian bool

Indicates 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 Stream

The input stream.

buffer byte[]

The buffer used for reading.

isLittleEndian bool

Indicates 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 Stream

The input stream.

buffer byte[]

The buffer used for reading.

isLittleEndian bool

Indicates if the value is in little-endian format.

len int

The 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 Stream

The input stream.

buffer byte[]

The buffer used for reading.

isLittleEndian bool

Indicates 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 Stream

The 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 string

The 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

data byte[]

The byte array to save.

fileName string

The file path to save the data to.

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 Stream

The stream whose contents to save.

fileName string

The 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 Type

The 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 string

The 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 string

The 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 long

The 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 StreamWriter

The 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 string

The 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 Stream

The output stream.

buffer byte[]

The buffer used for writing.

value byte

The 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 Stream

The output stream.

bytes byte[]

The byte array.

len int

The number of bytes to write.

pos int

The 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

stream Stream

The stream to write to.

value object

The object to write.

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 Stream

The output stream.

buffer byte[]

The buffer used for writing.

value int

The integer value to write.

isLittleEndian bool

Indicates 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 Stream

The output stream.

buffer byte[]

The buffer used for writing.

value long

The long value to write.

isLittleEndian bool

Indicates if the value is in little-endian format.

len int

The 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

stream Stream

The stream to write to.

buffer byte[]

The byte array to write.

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 Stream

The stream to write to.

value object

The 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 Stream

The output stream.

buffer byte[]

The buffer used for writing.

value short

The short value to write.

isLittleEndian bool

Indicates 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 Stream

The output stream.

buffer byte[]

The buffer used for writing.

value uint

The unsigned integer value to write.

isLittleEndian bool

Indicates 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 Stream

The output stream.

buffer byte[]

The buffer used for writing.

value ulong

The unsigned long value to write.

isLittleEndian bool

Indicates if the value is in little-endian format.

len int

The 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)

Parameters

stream Stream

The output stream.

buffer byte[]

The buffer used for writing.

value ushort

The unsigned short value to write.

isLittleEndian bool

Indicates if the value is in little-endian format.