Wednesday, 5 April 2017

Searching for a Specific Word in a Text File and Displaying in C#


      public static void Main()
        {
             Task.Run(async () => await Writefilecontent());
             Console.ReadLine();
         }


     private static async Task Writefilecontent()
        {
            string sourceFilePath = @"D:\Test\Source.txt";
            string destinationFilePath = @"D:\Test\Destination.txt";
            if (File.Exists(filepath))
            {
                var sb = new StringBuilder();
                var fs = new FileStream(sourceFilePath , FileMode.Open, FileAccess.Read);
                using (var sr = new StreamReader(fs))
                {
                    string line;
                    while ((line =await sr.ReadLineAsync()) != null)
                    {
                        if (line.Contains("this"))
                        {
                            sb.Append("this done !!!!!" + Environment.NewLine);
                        }
                    }
                }
                using (var sw = new StreamWriter(destinationFilePath , true)) // This is for writing text into some other file , you can do as your requirement. 
                {
                   await sw.WriteAsync(sb.ToString());
                }
                Console.WriteLine(sb.ToString());
                Console.ReadLine();
            }
        }

Note=> In StreamWriter we have to pass true other wise ,it will overwrite all text into  destination file.

like this

var sw = new StreamWriter(destinationFilePath , true)

No comments:

Post a Comment