簡體   English   中英

無法擴展MemoryStream…從FileStream到MemoryStream或類似的重構

[英]MemoryStream cannot be expanded…refactoring from FileStream to MemoryStream or similar

我在重構代碼塊時遇到問題。 我模糊地理解了問題,但是多一點洞察力和/或解釋將對我的理解和解決問題非常有幫助。

首先是原始代碼塊:

FileStream fS = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
Int64 fSLength = fS.Length;
Int64 remainingNotFulEncDecBlock = fSLength % 1;
fS.Seek(0, SeekOrigin.End);
Int64 nrBytesToAdd = 1 - remainingNotFulEncDecBlock;

Byte fillByte = (Byte)'$';

  for (Int32 i = 0; i < nrBytesToAdd - 1; i++)
    fS.WriteByte(fillByte);
    fS.WriteByte((Byte)nrBytesToAdd);
    fSLength = fS.Length;
    fS.Close();

重構的唯一目的是我們不再需要打開物理文件。 相反,我們提供了byte[]

這是我的重構代碼:

MemoryStream fS = new MemoryStream(_data);
Int64 fSLength = fS.Length;
Int64 remainingNotFulEncDecBlock = fSLength % 1;
fS.Seek(0, SeekOrigin.End);
Int64 nrBytesToAdd = 1 - remainingNotFulEncDecBlock;

Byte fillByte = (Byte)'$';
  for (Int32 i = 0; i < nrBytesToAdd - 1; i++)
    fS.WriteByte(fillByte);
    fS.WriteByte((Byte)nrBytesToAdd);
    fSLength = fS.Length;
    fS.Close();

上面的代碼產生錯誤MemoryStream不能在行上展開

fS.WriteByte((Byte)nrBytesToAdd);

最初,我不得不向Google搜索錯誤並進行閱讀。 現在這很有意義,因為內存流已設置為特定大小。 我尚不清楚應該如何進行。 我是否創建另一個未設置為特定大小的MemoryStream對象,從而允許我執行以下操作:

MemoryStream ms = new MemoryStream();
ms.WriteByte((Byte)nrBytesToAdd);

我對這項技術的閱讀表明,這比將MemoryStream初始化為指定的byte[]性能要差,但是我不知道(找不到)動態擴展MemoryStream另一種方法。 加號的是,現在和可預見的將來, byte[]會很小,因此雖然速度較慢可能不會對性能產生重大影響。

您可以使用具有初始容量的MemeoryStream 構造函數

MemoryStream fS = new MemoryStream(_data.Length);

這將設置該大小的內部字節數組,因此內存流不必在每次達到其大小限制時都繼續擴展該數組。 它將允許您將字節添加到內存流。 盡管不如擁有一個靜態byte []大小那么有效,但它可能是下一個最好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM