Write a C# program to print the noofcharacters , noof words,noof lines from a text file?

Q2. And also write a program to read the file from current directory and do the same operation 

//namespaces 

using System.IO;

using System;


class Program

{

    static void Main()

    {

        Console.WriteLine("Hello, World!");

       //below code line is used to get all filenames from the current directory 

       string[] _fileNamesInDirectory = Directory.GetFiles(Directory.GetCurrentDirectory());

       foreach(var item in _fileNamesInDirectory)

       {

       //below code is used to get the filepath for each file using directory and filename

        string filepath = Path.Combine(Directory.GetCurrentDirectory(), item);

         if(!string.IsNullOrEmpty(filepath))

        {

        //here we are getting the file extension     

         string extn = Path.GetExtension(filepath);  

        //here we are allowing all files except files with '.exe' extension

             if(extn!=".exe"){

             System.Console.WriteLine("File Name:"+item);

             System.Console.WriteLine("------------------");

            //we are calling print method which we have created in same class

             Print(filepath);

             System.Console.WriteLine("------------------");

             }

          }

       }

}

    static void Print(string filepath){

        // Read the file as one string.

        string text = System.IO.File.ReadAllText(filepath);

        string[] lines = System.IO.File.ReadAllLines(filepath);

        System.Console.WriteLine("File Path:"+filepath);

        System.Console.WriteLine("No Of Lines in Textfile:"+lines.Length);

        System.Console.WriteLine("No Of Characters in Textfile:"+text.Length);

        System.Console.WriteLine("No Of Words in Textfile:"+getCountofWordsFromString(text));

    }

    static int getCountofWordsFromString(string input){

        

        int index= 0 , noofWords = 1;

      

      while (index <= input.Length - 1) {

         if(input[index]==' ' || input[index]=='\n' || input[index]=='\t') {

            noofWords++;

         }

         index++;

      }

      

      return noofWords;

    }

}

Comments

Popular posts from this blog

Implement virtualisation in kendo drop down list using jquery ajax in mvc, aspx page

How to Create trigger to Update the NoofOrgs Count under each category in Category Table based on Temp Table in Sql Server

How to Preview the image and download which is in base64string format in mvc view using C#