2009-08-06

ConsoleColor extension methods

Sometimes we want to display some text on the console in some specified color (e.g. error in red, warning in yellow, etc). The procedure is often virtually identical, that is, it consists of three steps:

  1. Save the current color.
  2. Write the text on the console.
  3. Restore saved color.

As we can know, the duplication of code is not a good practice, therefore we should extract the first and the last step from the foregoing procedure, and encapsulate it into a nice class. The code located further in this post is an example of such class. The class can help with the mentioned task, and it’s usage is really easy and convenient – look at an example:

using (ConsoleColor.Red.AsForeground())
{
  Console.Error.WriteLine("Error… the application will now generate a lovely BSOD.");
}

The using keyword will guarantee us that the previous color will always be restored (in the compiler-generated finally clause).

In the implementation of the class you can see, that all console-related exception are caught and ignored. If you do not want to ignore these exceptions, you can always delete try-catch clauses, but remember, that the Dispose method must not throw any exception.

And finally, the code of the ConsoleColorExtension class:

C# Download ConsoleColorExtension.cs file
/// <summary>Extension methods for the ConsoleColor enum.</summary>
public static class ConsoleColorExtensions
{
  /// <summary>Provides an easy way to display messages in specified color.</summary>
  /// <param name="foregroundColor">The color in which the messages will be displayed.</param>
  /// <returns>An object which restores previous console foreground color on disposal.</returns>
  /// <example><code>
  /// using (ConsoleColor.Red.AsForeground())
  ///     Console.WriteLine("This should be red.");
  ///
  /// using (ConsoleColor.Cyan.AsForeground())
  /// using (ConsoleColor.Magenta.AsBackground())
  ///     Console.WriteLine("This should be cyan on magenta background.");
  ///
  /// Console.WriteLine("This should be displayed with default colors.");
  /// </code></example>
  public static IDisposable AsForeground(this ConsoleColor foregroundColor)
  {
    if (!Enum.IsDefined(typeof(ConsoleColor), foregroundColor))
      throw new ArgumentOutOfRangeException("foregroundColor");
    return new ConsoleColorizer(foregroundColor, true);
  }

  /// <summary>Provides an easy way to display messages on specified color.</summary>
  /// <param name="backgroundColor">The color on which the messages will be displayed.</param>
  /// <returns>An object which restores previous console background color on disposal.</returns>
  /// <example>See <see cref="M:ConsoleColorExtensions.AsForeground" /> for example.</example>
  public static IDisposable AsBackground(this ConsoleColor backgroundColor)
  {
    if (!Enum.IsDefined(typeof(ConsoleColor), backgroundColor))
      throw new ArgumentOutOfRangeException("backgroundColor");
    return new ConsoleColorizer(backgroundColor, false);
  }

  private sealed class ConsoleColorizer : IDisposable
  {
    public ConsoleColorizer(ConsoleColor cc, bool fore)
    {
      _fore = fore;
      try
      {
        _previousColor = _fore ? Console.ForegroundColor : Console.BackgroundColor;
        if (_fore) Console.ForegroundColor = cc;
        else Console.BackgroundColor = cc;
      }
      catch (Exception e)
      {
        if (!(e is ArgumentException || e is SecurityException || e is IOException)) throw;
      }
    }

    private bool _fore;
    private ConsoleColor? _previousColor;

    public void Dispose()
    {
      if (_previousColor.HasValue)
      {
        try
        {
          if (_fore) Console.ForegroundColor = _previousColor.Value;
          else Console.BackgroundColor = _previousColor.Value;
        }
        catch (Exception e)
        {
          if (!(e is ArgumentException || e is SecurityException || e is IOException)) throw;
        }
      }
      GC.SuppressFinalize(this);
    }
  }
}

Enjoy coloring the console :)

Kick it on DotNetKicks.com

2009-07-27

Wait until file is closed/unlocked

Sometimes you want to wait until some specified file is available for reading/writing. For example, you wait until other process finishes packing into a zip file, or wait until some file is fully uploaded to the server so you can compress it at server side, or something like that.
There are some solutions in which checking whether the file can be opened mainly looks like this:

public static bool IsFileAvailable(string path)
{
  try
  {
    if (!File.Exists(path)) return false;
    using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { };
    return true;
  }
  catch (Exception) { return false; }
}

There are some drawbacks to this approach. Imagine that this code returns true, but before we actually open the file, some other process or thread manages to open and lock the file. Besides, a generic exception should not be caught, because we might “eat” some really important exception like OutOfMemoryException or similar. A better solution would be to return obtained file stream, and catch only file-related exceptions.

After some refactoring, adding extension methods, and adding ‘wait’ methods, the final code looks like this:

C# Download TryOpenFile.cs file
public static class FileExt
{
  public static FileStream TryOpenFile(string path, FileAccess access, FileShare share)
  {
    try
    {
      if (!File.Exists(path)) return null;
      return File.Open(path, FileMode.Open, access, share);
    }
    catch (IOException) { return null; }
    catch (UnauthorizedAccessException) { return null; }
  }

  public static FileStream WaitAndOpenFile(string path, FileAccess access, FileShare share, TimeSpan timeout)
  {
    DateTime dt = DateTime.UtcNow;
    FileStream fs = null;
    while ((fs = TryOpenFile(path, access, share)) == null && (DateTime.UtcNow - dt) < timeout)
    {
      Thread.Sleep(250); // who knows better way and wants a free cookie? ;)
    }
    return fs;
  }

#region " Other Methods"
  public static FileStream TryOpenFileForReading(this FileInfo fileInfo) { return TryOpenFileForReading(fileInfo.FullName); }
  public static FileStream TryOpenFileForReading(string path) { return TryOpenFile(path, FileAccess.Read); }
  public static FileStream TryOpenFileForWriting(this FileInfo fileInfo) { return TryOpenFileForWriting(fileInfo.FullName); }
  public static FileStream TryOpenFileForWriting(string path) { return TryOpenFile(path, FileAccess.ReadWrite); }
  public static FileStream TryOpenFile(this FileInfo fileInfo, FileAccess access) { return TryOpenFile(fileInfo.FullName, access); }
  public static FileStream TryOpenFile(string path, FileAccess access) { return TryOpenFile(path, access, FileShare.None); }
  public static FileStream TryOpenFile(this FileInfo fileInfo, FileAccess access, FileShare share) { return TryOpenFile(fileInfo.FullName, access, share); }
  public static FileStream WaitAndOpenFileForReading(this FileInfo fileInfo, TimeSpan timeout) { return WaitAndOpenFileForReading(fileInfo.FullName, timeout); }
  public static FileStream WaitAndOpenFileForReading(string path, TimeSpan timeout) { return WaitAndOpenFile(path, FileAccess.Read, timeout); }
  public static FileStream WaitAndOpenFileForWriting(this FileInfo fileInfo, TimeSpan timeout) { return WaitAndOpenFileForWriting(fileInfo.FullName, timeout); }
  public static FileStream WaitAndOpenFileForWriting(string path, TimeSpan timeout) { return WaitAndOpenFile(path, FileAccess.ReadWrite, timeout); }
  public static FileStream WaitAndOpenFile(this FileInfo fileInfo, FileAccess access, TimeSpan timeout) { return WaitAndOpenFile(fileInfo.FullName, access, timeout); }
  public static FileStream WaitAndOpenFile(string path, FileAccess access, TimeSpan timeout) { return WaitAndOpenFile(path, access, FileShare.None, timeout); }
  public static FileStream WaitAndOpenFile(this FileInfo fileInfo, FileAccess access, FileShare share, TimeSpan timeout) { return WaitAndOpenFile(fileInfo.FullName, access, share, timeout); }
#endregion
}

This code also is not perfect. I known of no better method of waiting until a file is closed by the previous owner, except waiting in a loop. We can only make this method a little better by using the Thread.Sleep method which prevents CPU from being used all the time.

There is one more thing. Why is the FileShare.None flag used by default? Only because we do not want other processes/threads to mess with our file which we obtained with such “difficulties”.

Well… that is all for today. I hope this code will be helpful for you :)

Kick it on DotNetKicks.com

Hello World!

Greetings everyone :)

Time permitting, at this blog I will post usually simple code snippets which could be helpful in some situations, and other stuff related with programming… so stay alert ;)

Kick it on DotNetKicks.com