简体   繁体   中英

C# Pass a file via command line

My Programm is supposed to read the file and count the number of vowels and consonants in it. So, the fileName must be passed as a command line argument. This is part of my code:

class FileDetails 
{
    static void Main(string[] args) 
    {

        Console.WriteLine(args.Length); 
        foreach (string arg in args)
        { 
            Console.WriteLine(arg); 
        }
    }
}

After compilation of this file, I run it via command line and pass some arguments to the Main function:

C:\Users\StepN\Desktop\FILEDETAILS>filedetails abc def xyz

The result of programm looks like this:

3
abc
def
xyz

So, the root of the problem is that I need to pass as a command line argument the filename, but I don't know, how to do it.

Thanks in advance for any help!

class Program
{
    static void Main(string[] args)
    {
    if (args.Length == 0){
        Console.WriteLine("Please pass command line arguments.");
        return;
    }

    string fileName = args[0];

    }
}

If you are using spaces in one command line argument then enclose it with double quotes. That is how you should give arguments to your executable:

C:\Users\StepN\Desktop\FILEDETAILS>filedetails.exe "C:\file name.txt"

In Code access filename:

class FileDetails 
{
  static void Main(string[] args) 
  {
     if(args.Length > 0 )
     {
         string filePath = args[0];            

         //read the file using System.IO namespace
     }

   }
}

The only problem you can have is file name with white spaces. If your file has name abc def xyz then you should pass it wrapped in double quotes:

C:\Users\StepN\Desktop\FILEDETAILS>filedetails "abc def xyz"

There is a way to do.

1) Open Notepad and write your code and save it.

2) MOST IMPORTANT: Open visual studio command prompt and compile the code as follow: (i) Set current path, where your program is saved. (ii) Compile it with csc FileName.cs

3) Now execute the program using following command line argument: (a) FileName arg1 arg2

If you aren't comfortable doing this then create a batch file and pass write your arguments. Then run your .bat file which will trigger your C# program. I mean that this might trigger the .exe in your bin folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM