将数据写入文本文件中的特定位置

时间:2015-09-25 15:11:35

标签: vb.net

我需要在第30个位置写入现有的文本文件。我正在使用寻求但不工作。使用下面的代码。使用Startposition作为30。

Public Sub WriteToFile(ByVal data As DataTable, ByVal FileName As String, ByVal FieldLength As String, ByVal StartPosition As String)
        Dim sbColumnData As New StringBuilder

        Using writer = New StreamWriter(Directory.GetCurrentDirectory() + "\test.txt")
            For Each oRecord In data.Rows
                sbColumnData.Clear()
                If oRecord(0).ToString().Length < FieldLength Then
                    sbColumnData.Append(oRecord(0).ToString().PadRight(FieldLength))
                ElseIf oRecord(0).ToString().Length = FieldLength Then
                    sbColumnData.Append(oRecord.ToString())
                Else
                    sbColumnData.Append(oRecord.ToString().Substring(0, FieldLength))
                End If
                writer.Seek(0, StartPosition )

                writer.WriteLine(sbColumnData)
                writer.Flush()
            Next

        End Using

    End Sub

1 个答案:

答案 0 :(得分:0)

你的语法错了。试试:

writer.Seek(StartPosition, SeekOrigin.Begin)
writer.Write(sbColumnData, 0, sbColumnData.Length);

https://msdn.microsoft.com/en-us/library/system.io.filestream.seek%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396