简体   繁体   English

C#通过命令行传递文件

[英]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. 因此,必须将fileName作为命令行参数传递。 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: 编译完此文件后,我通过命令行运行它,并将一些参数传递给Main函数:

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: 如果您的文件名为abc def xyz ,则应使用双引号将其传递:

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. 1)打开记事本并编写代码并保存。

2) MOST IMPORTANT: Open visual studio command prompt and compile the code as follow: (i) Set current path, where your program is saved. 2)最重要的是:打开Visual Studio命令提示符并按如下所示编译代码:(i)设置当前路径,该路径用于保存程序。 (ii) Compile it with csc FileName.cs (ii)使用csc FileName.cs进行编译

3) Now execute the program using following command line argument: (a) FileName arg1 arg2 3)现在使用以下命令行参数执行程序:(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. 然后运行您的.bat文件,这将触发您的C#程序。 I mean that this might trigger the .exe in your bin folder. 我的意思是,这可能会触发bin文件夹中的.exe。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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