Как включить параметры опции "/ x" в консольное приложение .NET? - PullRequest
4 голосов
/ 21 июля 2010

Многие утилиты командной строки используют параметры, такие как:

gacutil /i MyDLL.dll

или

regasm /tlb:MyDll.tlb MyDll.dll

Как настроить консольное приложение .NET для приема аргументов командной строкии, во-вторых, как вы можете эмулировать обработку параметров "option", таких как /i и /tlb: в соответствующих примерах выше?

Ответы [ 7 ]

7 голосов
/ 21 июля 2010

Вы объявляете параметр для метода Main:

public static void Main(string[] args)

Теперь у вас есть массив, который для вашего первого примера содержит:

args[0] = "/i"
args[1] = "MyDLL.dll"

Вам просто нужно проанализировать строки, чтобы определить, что означает этот параметр. Что-то вроде:

foreach (string cmd in args) {
  if (cmd.StartsWith("/")) {
    switch (cmd.Substring(1)) {
      case "i":
        // handle /i parameter
        break;
      // some more options...
      default:
        // unknown parameter
        break;
    }
  } else {
    // cmd is the filename
  }
}
5 голосов
/ 21 июля 2010
1 голос
/ 21 июля 2010

Вы должны справиться с этим самостоятельно (или использовать существующую библиотеку) для работы с параметрами командной строки.См. MSDN (аргументы Main () и командной строки).

Одна хорошая библиотека - Mono.Options , другая, которую я использовал, - командная строка .

В вашем консольном приложении у вас будет метод main, который принимает параметр string[] (по умолчанию и условно), который называется args.Этот массив содержит все параметры командной строки.Затем вы можете разобрать их.

1 голос
/ 21 июля 2010

Вы просто заставляете свой метод Main принимать параметр string[]:

class Test
{
    static void Main(string[] args)
    {
        foreach (string arg in args)
        {
            Console.WriteLine(arg);
        }
    }
}

Вы должны соответствующим образом проанализировать аргументы, поскольку в платформе нет ничего встроенного.Возможно, вы захотите взглянуть на библиотеку NDesk.Options .(Есть много других, но это, кажется, популярно. Я не могу сказать, что сам использовал это, заметьте.)

0 голосов
/ 21 июля 2010

Я склонен писать свою собственную логику для этого, так как обычно я не хочу создавать дополнительную внешнюю зависимость для моего консольного приложения.

Ниже приведен код, который я написал для заполнения некоторых переменных с помощью аргументов командной строки. Этот код предназначен для поддержки префикса имен параметров с помощью «/» или «-» и, если параметр принимает значение (т.е. это не флаг), поддерживает отделение значения от имени с помощью «:» или «».

Прошу прощения за отсутствие комментариев;)

    static void Main(string[] args)
    {
        string directory = null;
        string filePattern = null;
        string sourceDirectory = null;
        string targetDirectory = null;
        List<string> version = null;
        string action = null;
        bool showHelp = false;

        for (int i = 0; i < args.Length; i++)
        {
            string parameterName;
            int colonIndex = args[i].IndexOf(':');
            if (colonIndex >= 0)
                parameterName = args[i].Substring(0, colonIndex);
            else
                parameterName = args[i];
            switch (parameterName.ToLower())
            {
                case "-dir":
                case "/dir":
                    if (colonIndex >= 0)
                    {
                        int valueStartIndex = colonIndex + 1;
                        directory = args[i].Substring(valueStartIndex, args[i].Length - valueStartIndex);
                    }
                    else
                    {
                        i++;
                        if (i < args.Length)
                        {
                            directory = args[i];
                        }
                        else
                        {
                            System.Console.WriteLine("Expected a directory to be specified with the dir parameter.");
                        }
                    }
                    break;
                case "-sourcedir":
                case "/sourcedir":
                    if (colonIndex >= 0)
                    {
                        int valueStartIndex = colonIndex + 1;
                        sourceDirectory = args[i].Substring(valueStartIndex, args[i].Length - valueStartIndex);
                    }
                    else
                    {
                        i++;
                        if (i < args.Length)
                        {
                            sourceDirectory = args[i];
                        }
                        else
                        {
                            System.Console.WriteLine("Expected a directory to be specified with the sourcedir parameter.");
                        }
                    }
                    break;
                case "-targetdir":
                case "/targetdir":
                    if (colonIndex >= 0)
                    {
                        int valueStartIndex = colonIndex + 1;
                        targetDirectory = args[i].Substring(valueStartIndex, args[i].Length - valueStartIndex);
                    }
                    else
                    {
                        i++;
                        if (i < args.Length)
                        {
                            targetDirectory = args[i];
                        }
                        else
                        {
                            System.Console.WriteLine("Expected a directory to be specified with the targetdir parameter.");
                        }
                    }
                    break;
                case "-file":
                case "/file":
                    if (colonIndex >= 0)
                    {
                        int valueStartIndex = colonIndex + 1;
                        filePattern = args[i].Substring(valueStartIndex, args[i].Length - valueStartIndex);
                    }
                    else
                    {
                        i++;
                        if (i < args.Length)
                        {
                            filePattern = args[i];
                        }
                        else
                        {
                            System.Console.WriteLine("Expected a file pattern to be specified with the file parameter.");
                            return;
                        }
                    }
                    break;
                case "-action":
                case "/action":
                    if (colonIndex >= 0)
                    {
                        int valueStartIndex = colonIndex + 1;
                        action = args[i].Substring(valueStartIndex, args[i].Length - valueStartIndex);
                    }
                    else
                    {
                        i++;
                        if (i < args.Length)
                        {
                            action = args[i];
                        }
                        else
                        {
                            System.Console.WriteLine("Expected an action to be specified with the action parameter.");
                            return;
                        }
                    }
                    break;
                case "-version":
                case "/version":
                    if (version == null)
                        version = new List<string>();
                    if (colonIndex >= 0)
                    {
                        int valueStartIndex = colonIndex + 1;
                        version.Add(args[i].Substring(valueStartIndex, args[i].Length - valueStartIndex));
                    }
                    else
                    {
                        i++;
                        if (i < args.Length)
                        {
                            version.Add(args[i]);
                        }
                        else
                        {
                            System.Console.WriteLine("Expected a version to be specified with the version parameter.");
                            return;
                        }
                    }
                    break;
                case "-?":
                case "/?":
                case "-help":
                case "/help":
                    showHelp = true;
                    break;
                default:
                    System.Console.WriteLine("Unrecognized parameter \"{0}\".", parameterName);
                    return;
            }
        }

        // At this point, all of the command line arguments have been read
        // and used to populate the variables that I defined at the top.
        // The rest of my application will work with the variables
        // and will not reference to args array again.
    }
0 голосов
/ 21 июля 2010

Точка входа приложения может быть объявлена ​​как:

static void Main (string[] args) { ... }

Это дает вам массив строк, в котором каждый элемент является одним из параметров командной строки.Как только вы это поймете, нужно просто проанализировать строки в массиве, чтобы настроить параметры в вашем приложении.

0 голосов
/ 21 июля 2010

Эта страница содержит пример VB.NET

Sub Main()
    Dim arrArgs() A s String = Command.Split(“,”)
    Dim i As Integer
    Console.Write(vbNewLine &amp; vbNewLine)
    If arrArgs(0) &lt;&gt; Nothing Then
        For i = LBound(arrArgs) To UBound(arrArgs)
            Console.Write(“Parameter “ &amp; i &amp; ” is “ &amp; arrArgs(i) &amp; vbNewLine)
        Next
    Else
        Console.Write(“No parameter passed”)
    End If
    Console.Write(vbNewLine &amp; vbNewLine)
End Sub

Эта страница MSDN содержит пример C #:

static int Main(string[] args)
{
    // Test if input arguments were supplied:
    if (args.Length == 0)
    {
        System.Console.WriteLine("Please enter a numeric argument.");
        System.Console.WriteLine("Usage: Factorial <num>");
        return 1;
    }

    // Try to convert the input arguments to numbers. This will throw
    // an exception if the argument is not a number.
    // num = int.Parse(args[0]);
    int num;
    bool test = int.TryParse(args[0], out num);
    if (test == false)
    {
        System.Console.WriteLine("Please enter a numeric argument.");
        System.Console.WriteLine("Usage: Factorial <num>");
        return 1;
    }
.....
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...