Search code examples
vb.netfile-uploadstreamreaderhttppostedfile

Save file if error reading with Stream Reader


I am trying to parse a uploaded txt file. I need to save the file if there is an error parsing it. The problem is that the parser is using a Stream Reader and if an error occurs it just saves the empty file and not the file contents.

Dim file As HttpPostedFile = context.Request.Files(0)
    If Not IsNothing(file) AndAlso file.ContentLength > 0 AndAlso Path.GetExtension(file.FileName) = ".txt" Then
        Dim id As Integer = (Int32.Parse(context.Request("id")))

        Try
            ParseFile(file, id)
            context.Response.Write("success")
        Catch ex As Exception
            Dim filename As String = file.FileName
            Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
            file.SaveAs(uploadPath + id.ToString() + filename)
        End Try
     Else
            context.Response.Write("error")
    End If

My ParseFile method is something like this

Protected Sub ParseFile(ByVal studentLoanfile As HttpPostedFile, ByVal id As Integer)
Using r As New StreamReader(studentLoanfile.InputStream)
        line = GetLine(r)
End Using
End Sub

Is there a way to Clone the file before it gets passed into the parseFile sub or a way to read the file without loosing the contents? Thanks in advance


Solution

  • For anyone who runs into this problem in the future, I ended up reading the file to the end and saving it into a variable. Then converted it back into a memory stream to use for the parser. If an error occurs, I just create a new file with the string. This is the code I used.

    Dim id As Integer = (Int32.Parse(context.Request("id")))
    
            'Read full file for error logging
            Dim content As String = [String].Empty
            Using sr = New StreamReader(uploadedFile.InputStream)
                content = sr.ReadToEnd()
            End Using
            'Convert it back into a stream
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(content)
            Dim stream As New MemoryStream(byteArray)
    
            Try
                ParseFile(stream, id, content)
                context.Response.Write("success")
            Catch ex As Exception
                Dim filename As String = uploadedFile.FileName
                Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
                'Save full file on error
                Using sw As StreamWriter = File.CreateText(uploadPath + id.ToString() + filename)
                    sw.WriteLine(content)
                End Using
                context.Response.Write("error")
                Throw ex
            End Try
        Else
            context.Response.Write("error")
        End If