Saturday, May 25, 2013

Console Application string extension to print/printline with color

public static class Extensions
    {

        public static string Print(this string content)
        {
            content.Print(null);
            return content;
        }

        public static string PrintLine(this string content)
        {
            content.PrintLine(null);
            return content;
        }

        public static string Print(this string content, ConsoleColor? fontColor)
        {
            if (fontColor.HasValue)
            {
                Console.ForegroundColor = fontColor.Value;
            }

            Console.Write(content);
            Console.ResetColor();

            Trace.Write(content);
            return content;
        }

        public static string PrintLine(this string content, ConsoleColor? fontColor)
        {
            if (fontColor.HasValue)
            {
                Console.ForegroundColor = fontColor.Value;
            }
            Console.WriteLine(content);
            Console.ResetColor();
            Trace.WriteLine(content);
            return content;
        }

        public static string Print(this string content, ConsoleColor? fontColor, ConsoleColor? backgroundColor)
        {
            if (fontColor.HasValue)
            {
                Console.ForegroundColor = fontColor.Value;
            }

            if (backgroundColor.HasValue)
            {
                Console.BackgroundColor = backgroundColor.Value;
            }
            Console.Write(content);
            Console.ResetColor();
            Trace.Write(content);
            return content;
        }

        public static string PrintLine(this string content, ConsoleColor? fontColor, ConsoleColor? backgroundColor)
        {
            if (fontColor.HasValue)
            {
                Console.ForegroundColor = fontColor.Value;
            }

            if (backgroundColor.HasValue)
            {
                Console.BackgroundColor = backgroundColor.Value;
            }


            Console.WriteLine(content);
            Console.ResetColor();
            Trace.WriteLine(content);
            return content;
        }

        public static byte[] GetBytes(this string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        public static string GetString(this byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
       
    }

No comments:

Post a Comment