尝试写入文件C#时出现System.FormatException

时间:2015-03-27 14:28:36

标签: c#

我有这个简单的程序,它在文本文件中读取一行,解析字典中的内容然后写入该内容 到一个文件。

上面提到的文本文件中的行是:

  

1433 =成员; 1064 = EndOfDayReportGeneration; 5679 = 1; 5678 = 22; 71 = 200602260亿; 3141 = ClrngETL; 72 = 20100301092024000; 2144 = CH004CR; 4059 = 20060226; 1828 = 20060226; 1823 = 20100301; 969 = 0048 ; 10003 = ACME CIMENT INC .; 1180 = TOUR OM。 ACMECIMENT 222 FRESNO COLLEGE AVE BUR 500,CA,MQ,H82 2P3; 1054 = true; 1055 = 5143502945; 1059 = JENNIFER ALLEY; 1058 = 5143502945; 1057 = TIM BROWN; 1056 = 5143502865; 1088 = LORD; 1089 = 12; 1090 = 5143502855; 773 =光学,幻觉; 1144 = 0000; 1195 = 1; 955 = ClientAccountProfile; 956 = ClearingMember; 1558 = 10000; 583 = {17 | 100}; 6385 = 20081208; 5049 = PPCD; 5578 = GA; 5579 = 000; 6143 = 20060226; 70 = 000000000; 73 = 20100301; 80 = 092024000; 2578 = 98138000

我得到System.FormatException:索引(基于零)必须大于或等于零 并且在尝试写入文件时小于参数列表的大小。

这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> dicParsed = new Dictionary<string, string>();

        try
        {
            StreamReader sr = new StreamReader("testFormat.txt");
            String line;
            line = sr.ReadLine();

            while (line != null)
            {
                dicParsed = line.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                 .Select(part => part.Split('='))
                 .ToDictionary(split => split[0], split => split[1]);
                string[] data = line.Split(null);

                line = sr.ReadLine();
            }

            //close the file
            if (sr != null)
            {
                sr.Close();
            }

        }
        catch (Exception except)
        {
            Console.WriteLine("Exception: " + except.Message);
        }
        finally
        {
            Console.WriteLine("Configuration File Parsed");
        }

        using (StreamWriter swLog = new StreamWriter("testLog.txt", true))
        {

            StringBuilder message = new StringBuilder("TEST "); 
            message.Append(Environment.NewLine);
            foreach (KeyValuePair<string, string> paires in dicParsed)
            {                    
                    message.Append(paires.Key.ToString() + "=" + paires.Value.ToString() + ";");
                    Console.WriteLine();
            }

            try
            {
                string test = message.ToString();
                swLog.Write(test, true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {

            }
        }
    }
} // end class program

1 个答案:

答案 0 :(得分:4)

您正在呼叫StreamWriter.Write(test, true)。我不知道为什么。这会调用StreamWriter.Write(string, object)重载,用于格式化打印字符串(如Console.WriteLine("Hello, {0}", name))。

您的test字符串包含{17|100},而不是{0},因此它会抛出。只需使用Write(string)重载。