Quick tip : redirect the console output to a file

In a console application, we use a lot the Console.WriteLine method.

We can redirect the output of the WriteLine method easily :


var consoleOut = Console.Out; // save the current output stream to be able to re-use it later

Console.SetOut(File.CreateText(@"C:\consoleout.txt")); // change the output stream for a file
 Console.WriteLine("a sample text"); // write some information

Console.SetOut(consoleOut); // reset the output to the console.

Stream.CopyTo method for < 4.0 framework

The .NET Framework 4.0 introduced the CopyTo() method for the Stream class. (http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx)

You copy a stream into one other this way:


   MemoryStream memoryStream = new MemoryStream();
   using (Stream stream = new FileStream(@"c:\input.txt", FileMode.Open))
   {
      stream.CopyTo(memoryStream);
   }

If you are stucked with a lower version of the framework, you might want to use it anyway.

A bit of reflector is realy usefull to see how the implementation is done in 4.0.

The CopyTo method :


public void CopyTo(Stream destination)
{
    if (destination == null)
    {
        throw new ArgumentNullException("destination");
    }
    if (!this.CanRead && !this.CanWrite)
    {
        throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
    }
    if (!destination.CanRead && !destination.CanWrite)
    {
        throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
    }
    if (!this.CanRead)
    {
        throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
    }
    if (!destination.CanWrite)
    {
        throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
    }
    this.InternalCopyTo(destination, 0x1000);
}

We see that the InternalCopyTo is used :


private void InternalCopyTo(Stream destination, int bufferSize)
{
    int num;
    byte[] buffer = new byte[bufferSize];
    while ((num = this.Read(buffer, 0, buffer.Length)) != 0)
    {
        destination.Write(buffer, 0, num);
    }
}

Remark :
0×1000 is in hexadecimal, which corresponds to 4096 in decimal.

So we can retrieve that for use with lower versions of the language

For .NET FX >= 3.0 you can create an extension method


    using System;
    using System.IO;

    /// <summary>
    /// Extension methods for streams.
    /// </summary>
    public static class StreamExtensions
    {
        /// <summary>
        /// Reads all the bytes from the current stream and writes them to the destination stream.
        /// </summary>
        /// <param name="original">The current stream.</param>
        /// <param name="destination">The stream that will contain the contents of the current stream.</param>
        /// <exception cref="System.ArgumentNullException">Destination is null.</exception>
        /// <exception cref="System.NotSupportedException">The current stream does not support reading.-or-destination does not support Writing.</exception>
        /// <exception cref="System.ObjectDisposedException">Either the current stream or destination were closed before the System.IO.Stream.CopyTo(System.IO.Stream) method was called.</exception>
        /// <exception cref="System.IO.IOException">An I/O error occurred.</exception>
        public static void CopyTo(this Stream original, Stream destination)
        {
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }
            if (!original.CanRead && !original.CanWrite)
            {
                throw new ObjectDisposedException("ObjectDisposedException");
            }
            if (!destination.CanRead && !destination.CanWrite)
            {
                throw new ObjectDisposedException("ObjectDisposedException");
            }
            if (!original.CanRead)
            {
                throw new NotSupportedException("NotSupportedException source");
            }
            if (!destination.CanWrite)
            {
                throw new NotSupportedException("NotSupportedException destination");
            }

            byte[] array = new byte[4096];
            int count;
            while ((count = original.Read(array, 0, array.Length)) != 0)
            {
                destination.Write(array, 0, count);
            }
        }
    }

You use it this way (same ways as the FX 4.0):


   MemoryStream memoryStream = new MemoryStream();
   using (Stream stream = new FileStream(@"c:\input.txt", FileMode.Open))
   {
      stream.CopyTo(memoryStream);
   }

For lower version, you can create an helper class.


    using System;
    using System.IO;

    /// <summary>
    /// An helper class for streams.
    /// </summary>
    public class StreamHelper
    {
        /// <summary>
        /// Reads all the bytes from the current stream and writes them to the destination stream.
        /// </summary>
        /// <param name="original">The original stream.</param>
        /// <param name="destination">The stream that will contain the contents of the current stream.</param>
        /// <exception cref="System.ArgumentNullException">Destination is null.</exception>
        /// <exception cref="System.NotSupportedException">The current stream does not support reading.-or-destination does not support Writing.</exception>
        /// <exception cref="System.ObjectDisposedException">Either the current stream or destination were closed before the System.IO.Stream.CopyTo(System.IO.Stream) method was called.</exception>
        /// <exception cref="System.IO.IOException">An I/O error occurred.</exception>
        public static void CopyStreamTo(Stream original, Stream destination)
        {
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }
            if (!original.CanRead && !original.CanWrite)
            {
                throw new ObjectDisposedException("ObjectDisposedException");
            }
            if (!destination.CanRead && !destination.CanWrite)
            {
                throw new ObjectDisposedException("ObjectDisposedException");
            }
            if (!original.CanRead)
            {
                throw new NotSupportedException("NotSupportedException source");
            }
            if (!destination.CanWrite)
            {
                throw new NotSupportedException("NotSupportedException destination");
            }

            byte[] array = new byte[4096];
            int count;
            while ((count = original.Read(array, 0, array.Length)) != 0)
            {
                destination.Write(array, 0, count);
            }
        }
    }

Use it this way:


   MemoryStream memoryStream = new MemoryStream();
   using (Stream stream = new FileStream(@"c:\input.txt", FileMode.Open))
   {
        StreamHelper.CopyStreamTo(stream, memoryStream);
   }
   

Incoming search terms:

  • FileStream CopyTo
  • stream copyto
  • Stream does not support reading
  • FileSteam CopyTo New Destination
  • C# FileStream CopyTo
  • stream copyto cannot access a closed stream
  • c# filestream to memorystream
  • c# filestream copyto example
  • c# filestream copyto count bytes
  • c# cannot access a closed stream copyTo

One line how to’s : Save text in a file, or read text from a file.

Sometimes your solution lies in a single line.

How to save a string in a text file


System.IO.File.WriteAllText("c://yourfile.txt",
"here is the content of my file !");

How to read a text file


string content =  System.IO.File.ReadAllText("c://yourfile.txt");

How does it work ?

A bit or Reflector gives us :

For the write method


public static void WriteAllText(string path, string contents)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
}
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM);
}

and the “InternalWriteAllText” method :


private static void InternalWriteAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter writer = new StreamWriter(path, false, encoding))
{
writer.Write(contents);
}
}

For the Read method :

public static string ReadAllText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    return InternalReadAllText(path, Encoding.UTF8);
}

And the “InternalReadAllText” :

private static string InternalReadAllText(string path, Encoding encoding)
{
    using (StreamReader reader = new StreamReader(path, encoding))
    {
        return reader.ReadToEnd();
    }
}

As you can see it don’t check if the file exists, so you have to check it by yourself :


if (System.IO.File.Exists("your file path"))
{
string content = System.IO.File.ReadAllText("your file path");
}

public static string ReadAllText(string path) { if (path == null) { throw new ArgumentNullException(“path”); } if (path.Length == 0) { throw new ArgumentException(Environment.GetResourceString(“Argument_EmptyPath”)); } return InternalReadAllText(path, Encoding.UTF8); }

Incoming search terms:

  • InternalReadAllText from iis read null
  • private static string internal readalltext(string path encoding encoding) asp net

JS Mixer is released

CSS mixer is really cool.  Good job.  Is there a JavaScript mixer?

It’s the main content of a mail I received last week.

It decided me to write a JS Mixer application, based on CSS Mixer.
The big part of the work was already done, I just needed to adapt my code.

Just like CSS Mixer, you can download it from codeplex : http://jsmixer.codeplex.com/

You can also download it from some software websites.

JSMixer antivirus scan report at softoxi.com

Remark :

With ASP.NET WebForms, you can achieve the same result by setting a few propertie to the ScriptManager control.

But the advantage to use a tool like JSMixer, is that your server doesn’t have to do the work : it’s already done !

And when you spare some work to your server, your server is happy !