是否可以使用数组中的值来修改VB.net中的变量?

时间:2015-05-23 13:40:48

标签: vb.net visual-studio-2013

我需要根据电子表格中输入的值在vb.net中创建多个文本文件。每个文本文件都将命名为“valuename.txt”。

我在输入值时使用值名称填充数组:

issues(j) = Grid1.Cells(1, j).Value

现在我需要用他们的名字打开文本文件。我想做一些事情:

 Dim Filename As String = "C:\" & Grid1.Cells(1, j).Value & ".txt"

 Dim issues(j) As New System.IO.StreamWriter(Filename)

当我在Visual Studio中输入它时,它说它不喜欢:

 issues(j)

我还有其他选择吗?

2 个答案:

答案 0 :(得分:2)

您发布的代码似乎是在for循环中,j是计数变量。

您已经从单元格值构建文件名,因此只需将该streamwriter声明为新变量并使用它:

For j = 0 To Grid1.Rows.Count - 1 'Assumed by me

    'Create the filename for the current row
    Dim Filename As String = "C:\" & Grid1.Cells(1, j).Value & ".txt"

    'The Using block makes sure that the ressources used by the streamwriter are disposed again.
    'It is equivalent as Dim sw As New IO.Streamwriter, but Using should be preferred
    Using sw As New IO.StreamWriter(Filename)
        'Use the streamwriter to write the data
    End Using

    'If you additionally want to store the values in an array for whatever reason       
     issues(j) = Grid1.Cells(1, j).Value 
Next

您的Dim issues(j)声明没有任何意义。

要将数据附加到现有文件,请使用StreamWriter构造函数的重载:

Using sw As New IO.StreamWriter(Filename, True)

第二个参数定义是否应将数据添加到文件中。

答案 1 :(得分:1)

您可以使用Using声明新的StreamWriter:

 Dim Filename As String = "C:\" & Grid1.Cells(1, j).Value & ".txt"

 Using fsw As New System.IO.StreamWriter(Filename)
     'Do Something
 End Using

但是如果你坚持使用StreamWriter列表(我不知道为什么)那么你可以这样做:

Dim fsw As New List(Of System.IO.StreamWriter)
fsw(j) = New System.IO.StreamWriter(Filename)
'Do Something
fsw(j).Close
fsw(j).Dispose