Showing posts with label learn c#. Show all posts
Showing posts with label learn c#. Show all posts

Friday, September 21, 2012

Beginner in C#: using StreamReader and StreamWriter

Brief Definition

StremReader: used to Read data from a file, such as .txt files.
StremWriter: used to Write data on a file, or even create a new file.

Example

To make things simple lets consider a simple example.
We want to write a C# console application that will EDIT a text file.
The process is as the following:
  1. Reading the old text file
  2. Writing a new one (edited one)
  3. Deleting the original.
Before you start make sure you've added this line above the namespace:
using System.IO;
In the following we suppose that you have a text file in the Debug directory of your project with name "file.txt".

Declarations:
            StreamReader sR = new StreamReader("file.txt");
            StreamWriter sW = new StreamWriter("new.txt");

Writing data in the new.txt file while reading from the file.txt file at the same time.
            while (sR.Peek() != -1) // stops when it reachs the end of the file
            {
                string line = sR.ReadLine();
                // "line" EDITING GOES HERE
                sW.WriteLine(line); // writing the edited line as a new line in the new.txt file
            }

Deleting the old file and rename the new file as the old file's name.
            File.Delete("file.txt");
            File.Move("new.txt", "file.txt");

Finally close the initially declared StreamReader and StreamWriter.
                sR.Close();
                sW.Close();
And that's it! leave your comments.

Beginner in C#: The if statement

The if statement is one of the most important statement in almost all programming languages and in C#.

The main use of it is to specify an action to do but only when a condition of type bool is true.


For example lets make a simple console application that asks the user for an integer number and determines if the number given is an even number or an odd number.

        static void Main(string[] args)
        {
            Console.Write("Enter a number: ");//asking the user to enter a number
            int number = int.Parse(Console.ReadLine());//reading the given number
            if (number % 2 == 0)//if 'number' is a multiple of two
                Console.WriteLine("It's an even number");//Writing the result
            else //this means "if not, do the following.."
                Console.WriteLine("It's an odd number");//Writing the result
            Console.Read();
        }

If (you have a question)
    Leave a comment and I'll answer!