Check Valid File Path in C#

1 Comment »

It’s not a trivial exercise to validate a file path on a Windows PC.  There are a few special cases depending on the file system and operating subsystem (source):

Read the rest of this entry »

Display an RTF File that’s a C# Embedded Resource

No Comments »

It’s easy to display an RTF file — that was embedded as a resource in a C# program — in a Windows Form RichTextControl.

Read the rest of this entry »

C# Copy Folder Recursively

2 Comments »

Sadly there is no built-in function in System.IO that will copy a folder and its contents.  Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed.  For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.

Read the rest of this entry »

C# Read Text File into String

2 Comments »

Here is the easiest way to read an entire text file into a C# string:

string s = System.IO.File.ReadAllText( path );

Truncate File Path with Ellipsis

4 Comments »

The Microsoft .NET Framework is quite comprehensive, but occasionally an obvious function slips through the cracks and you have to use InteropServices to access the Windows API.

One such obvious miss is the ability to truncate a file path. If you are drawing text and know the font and desired output size, you can use the WinForms TextRenderer class. But to truncate a file path to a specific number of characters, you need the “Shell Lightweight Utility Library” function PathCompactPathEx:

Read the rest of this entry »

List Drives and Volumes from .NET

No Comments »

The .NET Framework v2.0 did a nice job filling many holes in the System.IO namespace, especially when it comes to managing the file system. One such addition is the DriveInfo class, which enables you to determine what drives are available, their type, capacity and available free space.

Read the rest of this entry »

Console Output from a WinForms Application

5 Comments »

You may wish to enable your WinForms application to run from a console window or command line. And when it does, you probably want to send output messages to the console window that launched your WinForms application.

Unfortunately Console.WriteLine()–the standard method of writing to the console window–by default will not work from a WinForms application. That’s because the console window that launched your WinForms application belongs to the cmd.exe process, which is separate from your WinForms application process.

Read the rest of this entry »