2013-05-17 85 views
0

我想解析上傳的txt文件。如果解析出錯,我需要保存該文件。問題是解析器使用流讀取器,如果發生錯誤,它只保存空文件而不保存文件內容。保存文件,如果錯誤閱讀與流讀取器

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子或方法來讀取沒有鬆動的內容的文件克隆文件? 在此先感謝

+0

你在說什麼複製程序? – user973671

+0

用戶將要上傳文件,如果失敗,我只想保存它們。 – user973671

+0

如果在閱讀中發生崩潰,然後使文件損壞,您認爲您會保存什麼? ..最好先製作一個副本,然後上傳程序..如果上傳成功,那麼你可以刪除文件重複.. – matzone

回答

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