2013-05-21 28 views
0

我正在嘗試從sObj.txt中讀取文本&在MPadd.txt中寫入一些前綴文本。 sObj.txt包含一個垂直的單詞條(每行1個)&該文件中的行數是可變的(由用戶決定)。下面是我使用的腳本:獲取錯誤IndexOutOfRangeException未處理

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 

但在執行時會返回錯誤「IndexOutOfRangeException是未處理」還表示,指數數組的邊界之外。請幫忙。

回答

3

.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 
+0

你的代碼工作,但輸出是 stmotd -a WINFPH stmotd -b 15 WINFPH stmotd -a WINMAC stmotd -b 15 WINMAC stmotd -a WINPPC stmotd -b 15 WINPPC stmotd -a WINVPN stmotd -b 15 WINVPN 其中WINxxx是來自sObj.txt文件的文本。 不過,我需要這樣的輸出: stmotd -a WINFPH WINMAC WINPPC WINVPN stmotd -b 15 WINFPH WINMAC WINPPC WINVPN 能否請你幫忙嗎? – slyclam

+0

@slyclam請參閱編輯。 – GSerg

0

當你只有兩個項目在你的命令數組,如果導入從您的文件超過兩行,那麼你會增加兩倍以上counter多,所以你「會試圖在數組中訪問的項不存在,這意味着這一行:

SW.WriteLine(string.Format(commands(counter), line)) 

將導致index out of range錯誤。在.NET數組也是基於0的,所以應該counter在0開始的,除非你的意思是要排除的第一個項目objLines陣列中

編輯:是做你已經在你的評論中提及了你需要它更改爲以下:

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 
+0

有沒有一種方法可以根據命令從文件sObj.txt中打印多個條目?例如:stmotd -a WINFPH WINMAC WINPPC WINVPN stmotd -b 15 WINFPH WINMAC WINPPC WINVPN其中WINxxx是來自sObj.txt的條目 – slyclam

0

陣列「命令」中有隻有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 

如果你確定沒有。的命令數組中的項目,我會建議您硬編碼項目索引,而不是使用計數器變量。

+0

有沒有一種方法可以根據命令從文件sObj.txt中打印多個條目?例如: stmotd -a WINFPH WINMAC WINPPC WINVPN stmotd -b 15 WINFPH WINMAC WINPPC WINVPN 其中WINxxx是來自sObj.txt的條目 – slyclam

相關問題