我正在尝试从sObj.txt中读取文本,并在MPadd.txt中写入带有前缀的文本。sObj.txt包含一个垂直的单词条带(每行1个)&该文件中的行数是可变的(由用户决定)。下面是我使用的脚本:
Dim commands() =
    {
        "stmotd -a {0}",
        "stmotd -b 15 {0}"
    }
Dim counter As Integer = 1
Dim objLines = File.ReadAllLines("C:\temp\sObj.txt")
Using SW As New IO.StreamWriter("c:\temp\MPadd.txt", True)
    For Each line in objLines
        SW.WriteLine(string.Format(commands(counter), line))
        counter += 1
    Next
End Using但在执行时,它会返回错误“索引未处理”,还表示索引超出了数组的界限。请帮帮忙。
发布于 2013-05-21 18:13:41
.NET中的数组是从零开始的。
使用
Dim counter As Integer = 0显然,objLines包含的行不能超过两行。
也许您的意思是要为每一行发出所有commands?
For Each line in objLines
    For Each cmd in commands
        SW.WriteLine(string.Format(cmd, line))
    Next
Next编辑:
Dim joined_lines = File.ReadAllText("C:\temp\sObj.txt").Replace(vbNewLine, " ")
Using SW As New IO.StreamWriter("c:\temp\MPadd.txt", True)
    For Each cmd In commands
        SW.WriteLine(String.Format(cmd, joined_lines))
    Next
End Using发布于 2013-05-21 18:13:58
由于命令数组中只有两个项,因此如果从文件中导入超过两行,则会将counter递增两倍以上,因此您将尝试访问数组中不存在的项,这意味着下面这一行:
SW.WriteLine(string.Format(commands(counter), line))将导致index out of range错误。.NET中的数组也是从0开始的,因此counter应该从0开始,除非您打算排除objLines数组中的第一项
EDIT:是要执行您在评论中提到的操作,您需要将其更改为:
Using SW As New IO.StreamWriter("c:\temp\MPadd.txt", True)
    For Each cmd in commands
        Dim strLine As New String
        For Each line in objLines
            strLine += " WIN" + line
        Next
        SW.WriteLine(String.Format(cmd, strLine.ToUpper().Trim()))
    Next
End Using这会将数组中的所有项目附加到带有WIN前缀的一行中:
stmotd -a WINFPH WINMAC WINPPC WINVPN 
stmotd -b 15 WINFPH WINMAC WINPPC WINVPN发布于 2013-05-21 18:20:30
数组"commands“中只有2个项目。当计数器值为2时,它会抛出异常。我不确定您的要求,但您可以修改代码,如下所示:
Dim commands() =
    {
        "stmotd -a {0}",
        "stmotd -b 15 {0}"
    }
Dim counter As Integer = 0
Dim objLines = File.ReadAllLines("C:\temp\sObj.txt")
Using SW As New IO.StreamWriter("c:\temp\MPadd.txt", True)
      for Each line in objLines
      If counter > 1 Then
     counter = 0
      End If
      SW.WriteLine(string.Format(commands(counter), line))
      counter += 1
Next
End Using如果你确定不是。对于命令数组中的项,我建议您硬编码项索引,而不是使用计数器变量。
https://stackoverflow.com/questions/16667436
复制相似问题