Domanda

Sto cercando di passare argomenti della riga di comando a un'applicazione C #, ma ho problemi a passare qualcosa del genere

"C:\Documents and Settings\All Users\Start Menu\Programs\App name"

anche se aggiungo " " all'argomento.

Ecco il mio codice:

    public ObjectModel(String[] args)
    {
        if (args.Length == 0) return; //no command line arg.
        //System.Windows.Forms.MessageBox.Show(args.Length.ToString());
        //System.Windows.Forms.MessageBox.Show(args[0]);
        //System.Windows.Forms.MessageBox.Show(args[1]);
        //System.Windows.Forms.MessageBox.Show(args[2]);
        //System.Windows.Forms.MessageBox.Show(args[3]);
        if (args.Length == 3)
        {
            try
            {
                RemoveInstalledFolder(args[0]);
                RemoveUserAccount(args[1]);
                RemoveShortCutFolder(args[2]);
                RemoveRegistryEntry();
            }
            catch (Exception e)
            {
            }
        }
        }

Ed ecco cosa sto passando:

C:\WINDOWS\Uninstaller.exe  "C:\Program Files\Application name\"  "username"  "C:\Documents and Settings\All Users\Start Menu\Programs\application name"

Il problema è che posso ottenere correttamente il primo e il secondo argomento, ma l'ultimo viene visualizzato come C: \ Documents .

Qualche aiuto?

È stato utile?

Soluzione

Ho appena eseguito un controllo e verificato il problema. Mi ha sorpreso, ma è l'ultimo \ nel primo argomento.

"C:\Program Files\Application name\" <== remove the last '\'

Questo richiede ulteriori spiegazioni, qualcuno ha un'idea? Sono propenso a chiamarlo un bug.


Parte 2, ho eseguito qualche altro test e

"X:\\aa aa\\" "X:\\aa aa\" next

diventa

X:\\aa aa\
X:\\aa aa" next

Una piccola azione di Google fornisce alcune informazioni da un blog di Jon Galloway , le regole di base sono:

  • la barra rovesciata è il carattere di escape
  • evita sempre le virgolette
  • sfuggono alle barre rovesciate solo quando precedono una citazione.

Altri suggerimenti

Per aggiungere la risposta di Ian Kemp

Se l'assembly viene chiamato " myProg.exe " e passi nella stringa " C: \ Documents and Settings \ All Users \ Menu Start \ Programmi \ Nome app " link così

C:\>myprog.exe "C:\Documents and Settings\All Users\Start Menu\Programs\App name"

la stringa " C: \ Documents and Settings \ Tutti gli utenti \ Menu Start \ Programmi \ Nome app "

sarà su args [0].

Per aggiungere ciò che tutti gli altri hanno già detto, potrebbe essere un problema di fuga. Dovresti sfuggire alle tue barre rovesciate da un'altra barra rovesciata.

Dovrebbe essere qualcosa del tipo:

C: \ > myprog.exe " C: \\ Documents and Settings \\ All Users \\ Start Menu \\ Programmi \\ Nome app "

Di recente ho notato lo stesso fastidioso problema e ho deciso di scrivere un parser per analizzare personalmente gli argomenti della riga di comando.

Nota: il problema è che gli Argomenti .NET CommandLine passati alla funzione Main (string [] args) del vuoto statico sfuggono \ " e \\. Questo è di progettazione, dal momento che potresti voler passare un argomento che contiene una virgoletta o una barra rovesciata. Un esempio:

dire che si desidera passare il seguente come un singolo argomento:

  

-msg: Ehi, " Where you at? "

ad es.

  

sampleapp -msg: " Hey, \ " Where you   ? A \ " "

Sarebbe come inviarlo con il comportamento predefinito.

Se non vedi un motivo per cui nessuno deve scappare da virgolette o barre rovesciate per il tuo programma, potresti utilizzare il tuo parser per analizzare la riga di comando, come di seguito.

IE. [programma] .exe " C: \ test \ " arg1 arg2

avrebbe un args [0] = c: \ test " arg1 arg2

Quello che ti aspetteresti è args [0] = c: \ test \ e quindi args [1] = arg1 e args [2] = arg2.

La funzione seguente analizza gli argomenti in un elenco con questo comportamento semplificato.

Nota, arg [0] è il nome del programma usando il codice qui sotto. (Si chiama List.ToArray () per convertire l'elenco risultante in un array di stringhe.)

protected enum enumParseState : int { StartToken, InQuote, InToken };
public static List<String> ManuallyParseCommandLine()
{
    String CommandLineArgs = Environment.CommandLine.ToString();

    Console.WriteLine("Command entered: " + CommandLineArgs);

    List<String> listArgs = new List<String>();

    Regex rWhiteSpace = new Regex("[\\s]");
    StringBuilder token = new StringBuilder();
    enumParseState eps = enumParseState.StartToken;

    for (int i = 0; i < CommandLineArgs.Length; i++)
    {
        char c = CommandLineArgs[i];
    //    Console.WriteLine(c.ToString()  + ", " + eps);
        //Looking for beginning of next token
        if (eps == enumParseState.StartToken)
        {
            if (rWhiteSpace.IsMatch(c.ToString()))
            {
                //Skip whitespace
            }
            else
            {
                token.Append(c);
                eps = enumParseState.InToken;
            }


        }
        else if (eps == enumParseState.InToken)
        {
            if (rWhiteSpace.IsMatch(c.ToString()))
            {
                Console.WriteLine("Token: [" + token.ToString() + "]");
                listArgs.Add(token.ToString().Trim());
                eps = enumParseState.StartToken;

                //Start new token.
                token.Remove(0, token.Length);
            }
            else if (c == '"')
            {
               // token.Append(c);
                eps = enumParseState.InQuote;
            }
            else
            {
                token.Append(c);
                eps = enumParseState.InToken;
            }

        }
            //When in a quote, white space is included in the token
        else if (eps == enumParseState.InQuote)
        {
            if (c == '"')
            {
               // token.Append(c);
                eps = enumParseState.InToken;
            }
            else
            {
                token.Append(c);
                eps = enumParseState.InQuote;
            }

        }


    }
    if (token.ToString() != "")
    {
        listArgs.Add(token.ToString());
        Console.WriteLine("Final Token: " + token.ToString());
    }
    return listArgs;
}

In risposta alla risposta del WWC, Jamezor ha commentato che il suo codice fallirà se il primo carattere è una citazione.

Per risolvere quel problema, puoi sostituire il caso StartToken con questo:

            if (eps == enumParseState.StartToken)
            {
                if (rWhiteSpace.IsMatch(c.ToString()))
                {
                    //Skip whitespace
                }
                else if (c == '"')
                {
                    eps = enumParseState.InQuote;
                }
                else
                {
                    token.Append(c);
                    eps = enumParseState.InToken;
                }
            }

Qual è esattamente il problema? Comunque ecco alcuni consigli generali:

Assicurati che il tuo metodo Main (in Program.cs) sia definito come:

void Main(string[] args)

Quindi args è un array che contiene gli argomenti della riga di comando.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top