C# File Management Examples - Simple Console Programs for Absolute beginners

Before starting hands on practice for following  C# file management basic programs , I would recommend to please go through a very good article on File I/O.

Basic concepts of File I/O (Link here)

Now since we know little about the following keywords: 


File.CreateText, File.OpenText, File.AppendText, BinaryWriter, StreamReader, StreamWriter

We can easily understand and write the following simple programs.
(All the examples given in this blog have been tested with Visual Studio 2013).


Happy Coding!!:)


Problem 1:

Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt" 

Solution:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exerciseoops1
{
    class Program
    {
        static void Main(string[] args)
        {
                 string sentence = " ";
                 StreamWriter myfile;
                 myfile = File.CreateText("Test1.txt");
                         do
                         {
                             Console.Write("Enter a sentence");
                             sentence = Console.ReadLine();
                             if (sentence.Length != 0)
                             {
                                 myfile.WriteLine(sentence);
                             }
                         }
                         while (sentence.Length != 0);
                         myfile.Close();
                }
        }
    }


Problem 2:


Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt". If the file exists, the new content must be appended to its end.

Solution:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exerciseoops1
{
    class Program
    {
        static void Main(string[] args)
        {
                 string sentence = " ";
                 StreamWriter myfile;
                 myfile = File.CreateText("Test1.txt");
                         do
                         {
                             Console.Write("Enter a sentence");
                             sentence = Console.ReadLine();
                             if (sentence.Length != 0)
                             {
                                 myfile.WriteLine(sentence);
                             }
                         }
                         while (sentence.Length != 0);
                         myfile.Close();
                }
        }
    }


Problem 3:


Create a program to display all the contents of a text file on screen (note: you must use a StreamReader). The name of the file will be entered in the command line or (if there is no command line present) asked to the user by the program

Solution:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Exercisefile3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the name of the file");
            string nameFile = Console.ReadLine();
            StreamReader myfile;
                try
                {
                    myfile = File.OpenText(nameFile);
                    string line = "";

                            do
                            {
                                line = Console.ReadLine();
                                if (line != null)
                                    Console.WriteLine(line);

                            }
                            while (line != null);

                 }

                catch(Exception e)
                    {
                        Console.WriteLine("Error {0}", e);
                    }
                Console.ReadLine();
        }
    }
}


Problem 4:-


Create a class Logger, with a static method Write, which will append a certain text to a file: 
Logger.Write("myLog.txt", "This text is being logged"); 

It must also include the current date and time before the text (in the same line), so that the log file is easier to analyze. 

Solution:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Exercisefil3
{
    class Logger
    {

        public static void Write(string nameFile,string text)
        {
            StreamWriter myfile;
            myfile = File.AppendText(nameFile);
            myfile.WriteLine(DateTime.Now + " - " + text);
            myfile.Close();
        }
    }
}

Main Method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercisefil3
{
    class Program
    {
        static void Main(string[] args)
        {
            Logger.Write("text.txt", "hi how are you");
            //Console.ReadLine();
        }
    }
}


Problem 5:


Create a program to count the amount of times that a certain character is inside a file (of any kind). 

The file and the letter can be asked to the user or passed as parameters: 

count example.txt a 

It must display in screen the amount of letters found. 

(you can choose any way to interact with the user, showing the proper help) 

Solution:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

namespace Exercisefile8
{
    class Program
    {
        static void Main(string[] args)
        {

            bool debug = true;
            Console.WriteLine("Enter name of file");
            string filename = Console.ReadLine();
            Console.WriteLine("Enter the letter for count");
            string letter = Console.ReadLine();

            StreamReader myfile = File.OpenText(filename);
            string line;

            int countletter = 0;
                do
                {
                    line = myfile.ReadLine();
                    if (line != null)
                    {
                        for (int i = 0; i < line.Length; i++)
                        {
                            if (line.Substring(i, 1) == letter)
                                countletter++;
                        }
                    }
                }
                while (line != null);
                myfile.Close();

                Console.WriteLine("Count of letter {0}", countletter);

                if (debug)
                    Console.ReadLine();

        }
    }
}

Output:






Problem 6:


Create a program which asks the user for his name, his age (byte) and the year in which he was born (int) and stores them in a binary file. 

Create also a reader to test that those data have been stored correctly. 

Solution:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Exercisefil10
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your name");
            string name = Console.ReadLine();
            Console.WriteLine("Enter your age");
            Byte age = Convert.ToByte(Console.ReadLine());
            Console.WriteLine("Enter your date of Birth");
            int year = Convert.ToInt32(Console.ReadLine());

            BinaryWriter myfile = new BinaryWriter(File.Open("data.dat", FileMode.Create));
            myfile.Write(name);
            myfile.Write(age);
            myfile.Write(year);


            myfile.Close();

            string dataa;
            byte datab;
            int datac;

            BinaryReader file = new BinaryReader(File.Open("data.dat", FileMode.Open));
            dataa = file.ReadString();
            datab = file.ReadByte();
            datac = file.ReadInt32();

            file.Close();

            Console.WriteLine("Name {0} Age {1} Year {2}", dataa, datab, datac);

            if ((dataa != name) || (datab != age) || (datac != year))
                Console.WriteLine("Error in data");
            else
                Console.WriteLine("Read data ok");
            Console.ReadLine();


            
        }
    }
}


 Output:










Problem 7:

 Write a program to read a text file and dump its content to another file, changing the lowercase letters to uppercase. 

You must deliver only the ".cs" file, with you name in a comment. 

Solution:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

namespace Exercisefile16
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter name of the file");
            string filename = Console.ReadLine();
            if(File.Exists(filename))
            {
                StreamReader fileRdr = File.OpenText(filename);
                StreamWriter filewrt = File.CreateText(filename + ".dat");
                string line;
                do{
                    line = fileRdr.ReadLine();
                    if(line!= null)
                    {
                        filewrt.WriteLine(line.ToUpper());

                    }
                }
                while(line!= null);
                fileRdr.Close();
                filewrt.Close();
            }
        }
    }
}


Problem 8:


Create a C# program to count the amount of words stored in a text file 

Solution:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Exercisefile20
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader infile = File.OpenText("File.txt");
            string line;
            int wordscount = 0;
                do
                {
                    line = infile.ReadLine();
                        if(line != null)
                        {
                            string[] words = line.Split(' ');
                            wordscount += words.Length;
                        }

                }
                 while(line != null);

                Console.WriteLine("no. of Words {0}", wordscount);
                Console.ReadLine();
        }
    }
}



Problem 9:


Create a C# program to tell if two files (of any kind) are identical (have the same content). 

Solution:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Exercisefile31
{
    class Program
    {
        static void Main(string[] args)
        {
            bool equal = true;
            FileStream myfile1;
            byte[] datafile1;
            FileStream myfile2;
            byte[] datafile2;

            Console.WriteLine("Enter the name of file1");
            String filename1 = Console.ReadLine();
            Console.WriteLine("Enter the name of file2");
            String filename2 = Console.ReadLine();

            if ((!File.Exists(filename1)) || (!File.Exists(filename2)))
                Console.WriteLine("No file exists");
                try
                {
                    myfile1 = File.OpenRead(filename1);
                    datafile1 = new byte[myfile1.Length];
                    myfile1.Read(datafile1,0,(int)myfile1.Length);
                  

                    myfile2 = File.OpenRead(filename2);
                    datafile2 = new byte[myfile2.Length];
                    myfile2.Read(datafile2, 0, (int)myfile2.Length);
                    

                        if ((myfile1.Length) == (myfile2.Length))
                            for (int i = 0; i < datafile1.Length; i++)
                                if (datafile1[i] != datafile2[i])
                                    equal = false;
                        else
                               equal = false;
                        if (equal)
                            Console.WriteLine("File{0} is equal to {1}", filename1, filename2);
                        else

                            Console.WriteLine("File{0} is not equal to {1}", filename1, filename2);
                        myfile1.Close();
                        myfile2.Close();
                        Console.ReadLine();
                   }
            catch(Exception e)
            {
                Console.WriteLine("error" + e.Message);
            }
                Console.ReadLine();
            }
        }
    }



Problem 10:


Create a program to extract (only) the alphabetic characters contained in a binary file, and dump them to a different file. The extracted characters must be those whose ASCII code is 32 to 127, or 10, or 13. 

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Exercisefile34
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream file;
            Console.WriteLine("Enter the name of the file");
            string name = Console.ReadLine();
            if (!File.Exists(name))
                Console.WriteLine("No File Exists");
                try
                {
                    file = File.OpenRead(name);
                    byte[] bytesfile = new byte[file.Length];
                    file.Read(bytesfile, 0, (int)file.Length);
                    file.Close();
                    StreamWriter newfile = new StreamWriter(name + "01.txt");
                    for(int i =0;i<bytesfile.Length;i++)
                    {
                        if((Convert.ToInt32(bytesfile[i]) >=32 ) && (Convert.ToInt32(bytesfile[i]) <=127)
                            || (Convert.ToInt32(bytesfile[i]) == 10) || (Convert.ToInt32(bytesfile[i]) == 13))
                        {
                            newfile.Write(Convert.ToChar(bytesfile[i]));
                        }
                    }
                    newfile.Close();
                    Console.ReadLine();
                }
                catch(Exception e)
                {
                    Console.WriteLine("Error" + e.Message);
                }
                Console.ReadLine();
        }
    }
}