IOException未处理"进程无法访问该文件

时间:2015-10-13 15:55:06

标签: vb.net ssis

我正在尝试读取文件,重新格式化一些行,然后逐行覆盖文件。

我知道问题是因为打开现有文件两次,但我不知道如何修复它。

Public Sub Main()

    Dim objStreamReader As StreamReader
    Dim objWriter As StreamWriter

    If Dts.Variables("File").Value.ToString.Length > 0 Then


        'read the file
        objStreamReader = New StreamReader(Dts.Variables("File").Value.ToString)

        'write the file
        objWriter = New StreamWriter(Dts.Variables("File").Value.ToString)


        'read file line by line
        Dim row, line As String
        Dim isFirstRow As Boolean = True
        Dim numColumns As Integer = 0
        row = ""
        Do While objStreamReader.Peek() <> -1
            line = objStreamReader.ReadLine() 'read a line
            If line.Trim() = "" Then
                Continue Do 'skip blank line
            End If

            If isFirstRow Then 'first line in the file (it's always a complete row)
                numColumns = CountNumColumns(line) 'record the number of columns
                isFirstRow = False
                objWriter.WriteLine(line)
            ElseIf CountNumColumns(line) = numColumns Then
                'the line is a complete row
                objWriter.WriteLine(line)
            Else
                row = row & line
                If CountNumColumns(row) = numColumns Then
                    'we have a complete row
                    objWriter.WriteLine(row)
                    row = ""
                End If
            End If
        Loop

        'close files
        objStreamReader.Close()
        objWriter.Close()

    End If

    Dts.TaskResult = ScriptResults.Success
End Sub

'Counts the number of columns in a given line
Function CountNumColumns(ByVal line As String) As Integer
    Dim count As Integer = 0
    For index As Integer = 0 To line.Length - 1
        If line(index) = "|" Then
            count = count + 1
        End If
    Next
    Return count
End Function

0 个答案:

没有答案