1

I've been working on my module exercises and I came across this code snippet which reads the text file and prints the details about it.

It's working fine, but I just want to know how to give the path of the text file in the code itself other than giving the path in the command line.

Below is my code.

class Module06
{
   public static void Exercise01(string[] args)
    {
        string fileName = args[0];
        FileStream stream = new FileStream(fileName, FileMode.Open);
        StreamReader reader = new StreamReader(stream);
        int size = (int)stream.Length;
        char[] contents = new char[size];
        for (int i = 0; i < size; i++)
        {
            contents[i] = (char)reader.Read();
        }
        reader.Close();
        Summarize(contents);
    }

    static void Summarize(char[] contents)
    {
        int vowels = 0, consonants = 0, lines = 0;
        foreach (char current in contents)
        {
            if (Char.IsLetter(current))
            {
                if ("AEIOUaeiou".IndexOf(current) != -1)
                {
                    vowels++;
                }
                else
                {
                    consonants++;
                }
            }
            else if (current == '\n')
            {
                lines++;
            }
        }
        Console.WriteLine("Total no of characters: {0}", contents.Length);
        Console.WriteLine("Total no of vowels    : {0}", vowels);
        Console.WriteLine("Total no of consonants: {0}", consonants);
        Console.WriteLine("Total no of lines     : {0}", lines);
    }
}
1
  • This code does not use the .NET framework effectively. Okay for a language book I guess. But be sure to get another book that focuses on the framework. That's the other 90% you have to learn. Commented Mar 6, 2010 at 10:54

3 Answers 3

2

In your static void Main, call

string[] args = {"filename.txt"};
Module06.Exercise01(args);
Sign up to request clarification or add additional context in comments.

Comments

1

Reading of a text file is much easier with File.ReadAllText then you don't need to think about closing the file you just use it. It accepts file name as parameter.

string fileContent = File.ReadAllText("path to my file");

Comments

0
string fileName = @"path\to\file.txt";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.