【发布时间】:2014-01-17 13:41:19
【问题描述】:
下面是一段代码,它将数组重新编译为类似 csv 的文件。
Dim File As New System.IO.StreamWriter(varFileName)
Dim NumberOfRows As Long = Array.GetUpperBound(0) ' Count number of rows.
Dim NumberOfColumns As Long = Array.GetUpperBound(1) ' Count number of columns.
Dim FileRows(NumberOfRows) As String
File.Write("")
'The idea here is to make up the row first by adding all of the columns together then write each row to the file.
For i0 = 0 To NumberOfRows 'Loop through all of the Rows
For i1 = 0 To NumberOfColumns 'Loop through all of the Columns
If FileRows(i0) = "" Then 'Check if it is the first column then we dont need the ","
FileRows(i0) = Array(i0, i1) 'If it is the first column we start the row with the first column
Else
FileRows(i0) = FileRows(i0) + ","c + Array(i0, i1) 'Now we take what we have so far and add "," and add the the next column
End If
Next ' We repeat this process untill of of the columns are written to a row.
File.Write(FileRows(i0)) ' Now we write that row to the file.
Next ' Move on to the next row.
File.Close()
(请忽略我糟糕的编码习惯)
但是,如上所示,文件保存时没有新行,并且全部混合到一行中。
如果我将File.Write(FileRows(i0)) 行更改为File.WriteLine(FileRows(i0)),则会添加换行符,从而快速增加文件的大小。
我猜代码的第一个版本更正确,但我不确定如何解决缺少换行符的问题。任何帮助将不胜感激。 PS 稍微笨一点,我盯着这段代码看了两天,心都融化了。
将 csv 添加到数组代码中,以防出现问题。
Dim FileData As New System.IO.StreamReader(varFileName)
Dim FileRows() As String = FileData.ReadToEnd().Split(Environment.NewLine) 'Read in each row.
Dim NumberOfRows As Long = FileRows.GetUpperBound(0) ' Count number of rows.
Dim FileColumns() As String = FileRows(0).Split(","c) 'Split row 1 data in to columns.
Dim NumberOfColumns As Long = FileColumns.GetUpperBound(0) ' Count number of columns.
ReDim dataArray(NumberOfRows, NumberOfColumns) 'Declare the array correctly with new data
For x = 0 To NumberOfRows 'Cycle through all the rows
FileColumns = FileRows(x).Split(","c) 'Split row into columns
For y = 0 To NumberOfColumns 'Now cycle through all the columns on that row
Try
dataArray(x, y) = FileColumns(y) 'Set each piece of data into the array.
Catch ex As Exception
End Try
Next
Next
FileData.Close() 'This piece of code takes the csv file and turns it into an array. The data can now be called using Array(1,1) to get the first value
【问题讨论】:
-
您试图在不增加文件大小的情况下添加换行符?那是不可能的。但它不应该真的导致这么大的尺寸增加。
-
不幸的是,从文件中检索代码无法处理额外的行距