如何在上传中处理'System.OutOfMemoryException'?

时间:2013-04-04 10:48:46

标签: c# asp.net

加密后我在本地驱动器上传文档,我在web.config中有最大上传限制

 <httpRuntime maxRequestLength="2147483647" executionTimeout="1000"/>

当文档大小较大时,显示异常后的20mb

 Source Error: 
 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception 

 Stack Trace: 
 [OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
 System.IO.MemoryStream.set_Capacity(Int32 value) +93
 System.IO.MemoryStream.EnsureCapacity(Int32 value) +50
 System.IO.MemoryStream.WriteByte(Byte value) +130
 System.IO.BinaryWriter.Write(Byte value) +20
 System.Web.UI.SerializerBinaryWriter.WriteEncoded(Int32 value) +62
 System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +2081

 [ArgumentException: Error serializing value '644314' of type 'System.Int32.']
 System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +3371
 System.Web.UI.ObjectStateFormatter.Serialize(Stream outputStream, Object stateGraph) +141
 System.Web.UI.ObjectStateFormatter.Serialize(Object stateGraph) +57
 System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Serialize(Object state) +4
 System.Web.UI.Util.SerializeWithAssert(IStateFormatter formatter, Object stateGraph) +37
 System.Web.UI.HiddenFieldPageStatePersister.Save() +79
 System.Web.UI.Page.SavePageStateToPersistenceMedium(Object state) +108
 System.Web.UI.Page.SaveAllState() +315
 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2839

这个例外的原因是什么以及如何解决这个问题。

1 个答案:

答案 0 :(得分:3)

您不应将文件存储在ViewState中。它会对性能产生非常不利的影响(因为它会在每个后续请求中传输两次。

您需要将文件存储在临时文件夹中,然后将文件路径存储在ViewState中。请记住,您需要某种清理例程来删除(例如)一天之久的文件。