从命令行解析参数/参数

时间:2011-05-24 09:28:13

标签: c#

我将我的代码编辑为以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Search
{
    class Program
    {
        static void Main(string[] args)
        {
            string abc = string.Format("{0}", args[0]);
            string latestversion = string.Format("{1}", args[1]);
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "sslist.exe";
            p.StartInfo.Arguments = "-R -H -h sinsscm01.ds.net" + type;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.Start();
            string procOutput = p.StandardOutput.ReadToEnd();
            string procError = p.StandardError.ReadToEnd();
            TextWriter outputlog = new StreamWriter("C:\\Work\\listofsnapshot.txt");
            outputlog.Write(procOutput);
            outputlog.Close();
            string greatestVersionNumber = "";
            using (StreamReader sr = new StreamReader("C:\\Work\\listofsnapshot.txt")) 
            {
                while (sr.Peek() >= 0) 
                {
                    var line = sr.ReadLine();
                    var versionNumber = line.Replace(latestversion, "");
                    if(versionNumber.Length != line.Length)
                    greatestVersionNumber = versionNumber;
                }
            }
            Console.WriteLine(greatestVersionNumber);

            TextWriter latest = new StreamWriter("C:\\Work\\latestbuild.properties");
            latest.Write("Version_Number=" + greatestVersionNumber);
            latest.Close();
        }
    }
}

其中string typestring latest version是解析的参数。

所以,我的命令行看起来像这样:

c:/searchversion.exe "/SASE Lab Tools" "6.70_Extensions/6.70.102/ANT_RELEASE_"

其中"/SASE Lab Tools"应存储为字符串abc,而"6.70_Extensions/6.70.102/ANT_RELEASE_"应存储为latestversion字符串。

但是我得到一个错误:System.Format.Exception:Index(从零开始)必须大于或等于零且小于第14行的参数列表的大小:

string latestversion = string.Format("{1}", args[1]);

有人知道什么是错的吗?

3 个答案:

答案 0 :(得分:2)

string latestversion = string.Format("{0}", args[0]);

<强>更新

如果你去调试,你的args []是否填充了数据?

答案 1 :(得分:1)

代表

string latestversion = string.Format("{1}", args[1]); 

您指定了字符串格式数组中的第二项,但没有一项。所以这个数组是出界的。你的意思是

string latestversion = string.Format("{0}", args[1]); 

答案 2 :(得分:0)

请参阅abclatestversion是两个不同的字符串。由于您要逐个格式化,因此每次都需要将格式说明符设置为0。所以,你的代码应该是:

string latestversion = string.Format("{0}", args[1]); 
相关问题