Kshitij’s Blog .NET/ CSLA.NET / ASP.NET / VB.NET / C# / SQL Server / MySql ..
  • Dec
    8

    Add text to the beginning of a file using C#

    Filed under: C#;

    Hi,

    Few days back i needed a code snippet to write a text in starting of all files in a directory. Searched net but could not find any working code. Then i decide to write my own code and come up with following code.

    I hope this will help guys who are looking to do same.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace AddTextToFiles
    {
        class Program
        {
            private static DirectoryInfo ds;
            static void Main(string[] args)
            {
                Console.WriteLine("*********************Written By Kshitij Sharma ***********************");
                Console.WriteLine("Please Enter the path and Press enter ");
                string sPath = Console.ReadLine();
                Console.WriteLine("Please Enter <B style="BACKGROUND-COLOR: #a0ffff; COLOR: black">Text</B> ");
                string sText = Console.ReadLine();
                addText(sPath,sText);
                Console.WriteLine("*****************Reach Me @ k.sharma78@gmail.com****************");
                Console.Read();
            }
    
            private static void addText(string pth,string txt)
            {
                try
                {
    
                    if (!string.IsNullOrEmpty(pth))
                    {
                        ds = new DirectoryInfo(pth);
                    }
                    else
                    {
                        ds = new DirectoryInfo("c:\\testfiles");
                    }
                    if (string.IsNullOrEmpty(txt))
                    {
                        txt = "<!--#Include File=\"CheckSQL.inc\"-->";
                    }
                    foreach (FileInfo f in ds.GetFiles("*.asp"))
                    {
                        Console.WriteLine("Writing to file-->" + f.Name);
                        string strPath = ds.Root + ds.Name + "\\" + f.Name;
                        StreamReader sr = new StreamReader(strPath);
                        string fileContent = sr.ReadToEnd();
                        sr.Close();
                        StreamWriter sw = new StreamWriter(strPath, false);
                        StringReader gr = new StringReader(fileContent);
                        sw.WriteLine(txt);
                        sw.WriteLine(gr.ReadToEnd());
                        sw.Close();
                    }
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.Read();
                }
            }
        }
    }
    

    No Comments

Leave a Reply