Search code examples
c#file-iocommand-linefilestreamstreamreader

File-handling example problems


This is probably something I'm overlooking, but after running my program, I keep returning:

"ListIT could not find the file"

Here is my code:

public static void Main(string[] args)
{
    try {
        int ctr = 0;
        if (args.Length <= 0)
        {
            Console.WriteLine("Format: ListIT filename");
            return;
        }
        else
        {
            FileStream f = new FileStream(args[0], FileMode.Open);
            try
            {
                StreamReader t = new StreamReader(f);
                string line;
                while((line = t.ReadLine()) != null)
                {
                    ctr++;
                    Console.WriteLine("{0}: {1}", ctr, line);
                }
                f.Close();
            }
            finally { f.Close(); }
        }
    }
    catch(System.IO.FileNotFoundException)
    {
        Console.WriteLine ("ListIT could not find the file ", args[0]);
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: {0}\n\n", e);
    }
}

And here is my input into the command line:

csc.exe ex47_1.exe [Enter]
ex47_1.exe listit ex47_1.cs [Enter]

Any Suggestions? I'm fairly new to C#.

Edt: I've been teaching myself programming over the past 4 years, and this was the first time I used a Sam's Teach Yourself book. I didn't realize how many errors are in all the examples. Thank you for your help, but this taught me not to totally rely on the source to have everything correct.


Solution

  • I am not sure how running C# programs from command line, however, if I remember correctly in C++ when starting a program from the command line, the first argument is the name of the program.

    I.E.

    (Command Line Input) myProgram.exe myArgFile.txt

    Args[0] == "myProgram.exe" Args[1] == "myArgFile.txt"

    Are you meaning to look at Args[1] instead of Args[0]?

    UPDATE: What was said above does not apply to C#, however in this instance your code is trying to find file "listit" which is your Args[0]. What I believe you want is your "ex47_1.cs" file which is Args[1]. So change:

    FileStream f = new FileStream(args[0], FileMode.Open);
    

    to

    FileStream f = new FileStream(args[1], FileMode.Open);