首页 > 解决方案 > 我必须将列表中的数字添加到文件中

问题描述

这是我的代码,但每次我尝试编译它时,我都会收到此错误:

System.IndexOutOfRangeException:索引超出了数组的范围。

using System;
using System.Collections.Generic;
using System.IO;

namespace nrinfile
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers= new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
            string[] folderLoc = File.ReadAllLines(@"E:\folder\numbers.txt");
            for (int i = 0; i < 12; i++)
            {
                folderLoc[i] = Convert.ToString(numbers[i]);
            }
        }
    }
}`

标签: c#listfile

解决方案


不能保证至少folderLoc物品 _12

        for (int i = 0; i < 12; i++) {...}

你可以这样写(注意folderLoc.Length而不是12):

        string[] folderLoc = File.ReadAllLines(@"E:\folder\numbers.txt");

        // If you want at most 12 items to be changed put the condition as 
        //   i < Math.Max(12, folderLoc.Length)
        for (int i = 0; i < folderLoc.Length; i++)
        {
            folderLoc[i] = $"{i} {folderLoc[i]}"; //TODO: Apply the correct format here
        }

甚至(没有显式循环,但Linq查询)

        using System.Linq;

        ...

        string[] folderLoc = File
          .ReadLines(@"E:\folder\numbers.txt")
          .Select((value, index) => $"{index} {value}")
          .ToArray();

如果您只想更改顶12行,则应该Select

         ...
         .Select((value, index) => index < 12 ? $"{index} {value}" : value)
         ...

最后,如果您只想将0..11数字写入文件

         File.WriteAllLines(@"E:\folder\numbers.txt", Enumerable.Range(0, 12));

推荐阅读