C# – Delete all files in a directory

Use Directory.EnumerateFiles() to get the file paths in a directory. Then loop over the file paths and delete each file. Here’s an example: This deletes the root directory’s files without deleting the directory itself. I’ll show more examples. Delete all files with a specific extension Use Directory.EnumerateFiles’ searchPattern pattern to search for files with a … Read more

C# – How to make a file read-only

There are two ways to programmatically make a file read-only: Here’s an example showing both ways to make a file read-only: Using File.SetAttributes() is useful when you want to manage all of file’s attributes at once. FileAttributes is an enum flag, so you can use bitwise operations to add/remove multiple attributes at once. That’s why … Read more

C# – Search for files in a directory

Use Directory.EnumerateFiles() to search for files in a directory and then loop over the file paths (and then reading the files, or whatever you want to do with the info). Here’s an example of searching for files containing “hello” in the file name: Note: Use the wildcard character * to match anything. It returns an … Read more

C# – Check if a directory is empty

The simplest way to check if a directory is empty is by calling Directory.EnumerateFileSystemEntries(). If this doesn’t return anything, then the directory doesn’t have any files or subdirectories (folders), which means it’s empty. Here’s an example: Another situation to consider is when a directory has no files but might have empty subdirectories (folders). You can … Read more

C# – How to implement the plugin pattern

In this article, I’ll explain how to implement the plugin pattern. This approach uses a generic plugin loader that solves many real world problems when loading plugins in .NET. Besides being generic, this plugin loader also solves the following real world problems when working with plugins: If you find that this generic plugin loader doesn’t … Read more