我在安裝了16GB RAM的64位Windows 7計算機上的開發IIS服務器(來自VS2010 IDE)上運行以下方法:public static MemoryStream copyStreamIntoMemoryStream(Stream stream){ long uiLen = stream.Length; byte[] buff = new byte[0x8000]; int nSz; MemoryStream ms = new MemoryStream(); try { while ((nSz = stream.Read(buff, 0, buff.Length)) != 0) { ms.Write(buff, 0, nSz); } } finally { Debug.WriteLine("Alloc size=" + ms.Length); } return ms;}我得到了System.OutOfMemoryException這一行:ms.Write(buff, 0, nSz);分配268435456字節時拋出該錯誤:分配大小= 268435456這是0x10000000或256 MB。所以我想知道是否需要設置一些全局設置才能使其正常工作?
3 回答

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
我知道這很舊,但是我想知道Stream.CopyTo()方法是否不能解決小于int.MaxValue的流長度的內存分配問題?在這種情況下,以下代碼可能不太容易出現OutOfMemory異常: if (int.MaxValue >= memoryStream.Length) { MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); memoryStream.Capacity = (int) memoryStream.Length; // Optional but helps eliminate null padding. }
- 3 回答
- 0 關注
- 1458 瀏覽
添加回答
舉報
0/150
提交
取消