Work with files/dirs
2023-10-12 C# path directory file System.IO EnumerateFiles GetFullPath Combine GetFileName ReadAllText Encrypt DecryptHere are notes about useful methods to work with paths, directories, and files. I keep searching for them all the time, so brief summary of what I usually need would be good.
System.IO.Path class
Works on strings that represent logical path to file or a directory. Provides many useful static methods like
Path.GetFullPath
- returns an absolute path from a relative path. Can work against both current directory or specified base pathPath.Combine
- combines number of strings into a pathPath.Exists
- checks existence of entity referenced by specified pathPath.GetDirectoryName
- gets directory portion of the pathPath.GetFileName
andPath.GetFileNameWithoutExtension
- get file name from the pathPath.GetExtension
- returns file extension
System.IO.Directory class
Static methods to work on directories like copying, moving, enumerating them.
I use the Directory.EnumerateFiles
very often to find files across many input directories and their subdirectories:
foreach (string file in inputDirectories.SelectMany(
dir => Directory.EnumerateFiles(dir, "*.xls*", SearchOption.AllDirectories)))
{
ProcessFile(file);
}
Other useful methods are EnumerateDirectories
, Create
, Delete
, Exists
, or Move
.
System.IO.File class
Many tools to work with files, from Open
, Exists
, ReadAllLines
, ReadAllText
to Copy
and Move
.
Interesting functionality that can come handy on Windows platform that can use NTFS Encrypting File System (EFS) are methods Encrypt
and Decrypt
that provide protection that allow to decrypt only by same account who encrypted it.