Thursday, 30 January 2014

How to Read Text from a File in c#.net

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

namespace How_to_Read_Text_from_a_File
{
    class Program
    {
        public static void Main()
        {
            try
            {
                using (StreamReader sr = new StreamReader("adi.txt"))
                {
                    String line = sr.ReadToEnd();
                    Console.WriteLine(line);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
                
            }
            Console.ReadLine();
        }
    }
}
 
 

How to Write Text to a File

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

namespace Write_Text_to_a_File
{
    class Program
    {
        static void Main(string[] args)
        {
            string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            StringBuilder sb = new StringBuilder();

            foreach (string txtName in Directory.EnumerateFiles(mydocpath, "*.txt"))
            {
                using (StreamReader sr = new StreamReader(txtName))
                {
                    sb.AppendLine(txtName.ToString());
                    sb.AppendLine("Hi friends.......!");
                    sb.Append(sr.ReadToEnd());
                    sb.AppendLine();
                    sb.AppendLine();
                }
            }

            using (StreamWriter outfile = new StreamWriter(mydocpath + @"\TxtFiles.txt"))
            {
                outfile.Write(sb.ToString());
            }
        }
    }
}