如果使用Stream Reader读取错误,请保存文件

时间:2013-05-17 17:16:53

标签: vb.net file-upload streamreader httppostedfile

我正在尝试解析上传的txt文件。如果解析它时出错,我需要保存文件。问题是解析器正在使用Stream Reader,如果发生错误,它只保存空文件而不是文件内容。

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

我的ParseFile方法是这样的

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

有没有办法在文件传递到parseFile子类之前克隆文件或者在不丢失内容的情况下读取文件的方法? 提前致谢

1 个答案:

答案 0 :(得分:0)

对于将来遇到此问题的任何人,我最终将文件读到最后并将其保存到变量中。然后将其转换回内存流以用于解析器。如果发生错误,我只需使用字符串创建一个新文件。这是我使用的代码。

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