reading and writing a string as if it were a file. - CSharp File IO

CSharp examples for File IO:String Reader Writer

Description

reading and writing a string as if it were a file.

Demo Code



using System;/*from  w  w  w  .  j ava2 s .c o  m*/
using System.IO;
using System.Text;

public class Program
{
    public static void Main(string[] args)
    {
        string input = "this is a test";
        Console.WriteLine("Original text:\n{0}", input);

        StringReader reader = new StringReader(input);
        StringWriter writer = new StringWriter();

        string line = reader.ReadLine();
        Console.WriteLine("\nReading first line:\n{0}", line);

        writer.WriteLine(line);

        Console.WriteLine("\nWriting the line read to a StringWriter:\n{0}", writer.ToString());

        Console.WriteLine("\nReading characters from a string:");


        input = "this is a test";
        Console.WriteLine("Original text:\n{0}", input);

        reader = new StringReader(input);
        writer = new StringWriter();

        Console.WriteLine("\nReading the next 5 chars:");
        char[] buffer = new char[5];
        int x = reader.ReadBlock(buffer, 0, 5);
        foreach (char c in buffer) Console.Write(c);
        Console.WriteLine();

        input = "this is a test";
        Console.WriteLine("Original text:\n{0}", input);

        reader = new StringReader(input);
        writer = new StringWriter();

        Console.WriteLine("\nReading the next 5 chars:");
        buffer = new char[] { 'a' };

        writer.Write(buffer);
        Console.WriteLine("\nWriting the chars to a StringWriter:\n{0}", writer.ToString());


    }
}

Result


Related Tutorials