2

I am very new to c# and Im having issues trying to understanding this. How to pass a parameter to (or from I tend to confuse the terminology) the main function in order to read a text file? I have a python function that better shows what I want to do.

def readFile(filename):
    data = []
    source = file(filename)
    for line in source:
        words = line.split()
        for word in words:
            data.append(int(word))
    source.close()
    return data

I have a basic understanding of how to open files in c# but scouring the web I can't find anything that can help me do what I want or at least help translate. here's my basic understanding:

using System;
using System.Text;
using System.IO;

public class Readingfiles {


public static void Main()
{
    StreamReader src = new StreamReader("Data.txt");

    while(!src.EndOfStream)
    {
        string line = src.ReadLine();
        Console.WriteLine(line);
    }

  }
}

Please help, If it helps, Im using sublime text and compiling on terminal through mcs/mono.

Arj 1411
  • 1,395
  • 3
  • 14
  • 36

2 Answers2

3

You should have input argument args for your main():

static void Main(string[] args)

As an example:

class Program {
    static void Main(string[] args) {
        Console.WriteLine("This is the program");
        if (args == null || args.Length == 0) {
            Console.WriteLine("This has no argument");
            Console.ReadKey();
            return;
        }
        Console.WriteLine("This has {0} arguments, the arguments are: ", args.Length);
        for (int i = 0; i < args.Length; ++i)
            Console.WriteLine(args[i]);
        Console.ReadKey();
    }
}

The program will show you if you call the .exe with argument or not:

C:\Release> ConsoleApplication.exe //has no argument
C:\Release> ConsoleApplication.exe Data.txt //has one argument
C:\Release> ConsoleApplication.exe CallWith Data.txt //has two arguments
C:\Release> ConsoleApplication.exe "CallWith Data.txt" //has ONE arguments

In your case, likely the argument is just a single string, thus, putting the input checking on args[0] will be enough:

public static void Main(string[] args)
{
    if (args == null || args.Length == 0) {
        Console.WriteLine("Error: please specify the file to read!");
        Console.ReadKey();
        return;
    }

    try {

        StreamReader src = new StreamReader(args[0]);

        while(!src.EndOfStream)
        {
            string line = src.ReadLine();
            Console.WriteLine(line);
        }
    } catch (Exception ex) {
        Console.WriteLine("Error while reading the file! " + ex.ToString());
    }

    Console.ReadKey();    
}

Edit:

Your final solution should look like this (simply put the Main block to the correct namespace and class) and you should use all the usings:

using System;
using System.IO;

namespace ConsoleApplication2 {
    class Program {
        public static void Main(string[] args) {
            if (args == null || args.Length == 0) {
                Console.WriteLine("Error: please specify the file to read!");
                Console.ReadKey();
                return;
            }

            try {

                StreamReader src = new StreamReader(args[0]);

                while (!src.EndOfStream) {
                    string line = src.ReadLine();
                    Console.WriteLine(line);
                }
            } catch (Exception ex) {
                Console.WriteLine("Error while reading the file! " + ex.ToString());
            }

            Console.ReadKey();
        }
    }
}
Ian
  • 30,182
  • 19
  • 69
  • 107
  • this is good and I think this is exactly what I need, but, the function to open the text file will then have to use the information in the text file for other functions in a class, if I called the text opening file in main will it complete it the same way? – user1712507 Apr 24 '16 at 05:24
  • If you need to store the information for other functions, I suggest you two more things: (1) create a `List texts` or `string[] texts` to get the texts in your input file and use the `texts` in all other functions. (2) Put infinite while loop in your main function (`while(true)`) such that it won't be close before you specifically call `Application Exit` – Ian Apr 24 '16 at 05:26
  • so i copied your second example and it said "Unexpected symbol `end-of-file'" but end-of-file isnt in your code. – user1712507 Apr 24 '16 at 05:41
  • Which line does the error occur? I only give example for the main code. You need to include some `using` in your header part of the file... As long as you have all libraries, it should be OK. Also, the full file should contain the namespace and the class name. This is what you already did for your app: `using System; using System.Text; using System.IO; public class Readingfiles` – Ian Apr 24 '16 at 05:45
  • found the issue missed a bracket gawd im a newb – user1712507 Apr 24 '16 at 05:49
  • @user1712507 strange, can you edit your question with the `edit` option and then put up the updated code (*without* deleting your original post)? Also, please put some comments where the compiler gives you error in the additional codes. – Ian Apr 24 '16 at 05:52
  • yea it runs,but it wouldnt let me type, it just ended the code. – user1712507 Apr 24 '16 at 05:59
  • @user1712507 you got to run from command prompt. Checkout my example, it is run from the command prompt, just like how you normally run an exe application. – Ian Apr 24 '16 at 05:59
  • yea Im running it through terminal, using my mac right now, is that the issue? i type in mcs readc#.c mono readc#.exe – user1712507 Apr 24 '16 at 06:04
  • i wana kiss you rn like i wana figgen kiss you thanks man if I have any question im comin to you! – user1712507 Apr 24 '16 at 06:19
  • lol u no problem, you just did more for me than you think lol :) – user1712507 Apr 24 '16 at 06:43
1

You can acces command line arguments from any place of your program using

string[] args = Environment.GetCommandLineArgs();

Also, the simplest way to read all lines in the file is

if (args.Length > 1)    //the 1st is always the path to app
    string[] lines = System.IO.File.ReadAllLines(ards[1]);
Artem
  • 1,535
  • 10
  • 13