[英]MemoryStream output to a file c#
我有以下代碼:
string fileName = GetFileName();
using (var stream = new MemoryStream())
{
using (var sw = new StreamWriter(stream))
{
for (int i = 0; i < 20; i++)
{
sw.WriteLine(String.Format("{0};{1};{2};{3};{4};{5}", i.ToString(), (i*2).ToString(), "-_-_-", "-_" + i.ToString() + "_-", "3", "15"));
}
// Check if compression needed.
if (stream.Length > limit)
{
sw.Flush();
stream.Position = 0;
using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile())
{
absoluteFileName = Path.GetFileName(fileName);
zipFile.AddEntry(absoluteFileName, stream);
zipFileName = Path.Combine(Path.GetDirectoryName(fileName), Path.ChangeExtension(absoluteFileName, ZipExtension));
zipFile.Save(zipFileName);
}
}
else
{
// no compression needed
using (FileStream file = new FileStream(fileName, FileMode.Create, System.IO.FileAccess.Write))
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
file.Write(bytes, 0, bytes.Length);
//stream.Close();
}
}
}
我試圖生成一個純文本文件,以防memorystream長度(以字節為單位)不大於具體的字節數(限制(請參閱條件))。
如果memorystream長度大於具體的字節數,則創建一個壓縮文件。
我的問題是在else正文中,當我在不需要壓縮時嘗試將內存流的所有內容寫入純文本文件時(stream.Length <=限制)。 我得到一個39bytes的文件,但是當我打開它時,它是空的,里面只有新行。
我這樣做是因為我不想在需要壓縮的情況下直接在磁盤上創建文件。 因此,如果最后不需要壓縮,則將所有流內存寫入文件,這就是問題所在,文件為空,只有換行符。
我究竟做錯了什么?
UPDATE2我在條件語句之前放在了下面一行:
sw.Flush();
stream.Position = 0;
現在,內容已寫入文件。
我的問題是在其他身體
好吧,您用與第一個if
主體不同的方式來處理它。
在第一個if
正文中,您顯式刷新了writer並倒回了流:
sw.Flush();
stream.Position = 0;
您不會在else
主體中執行任何一項操作,因此不會獲得任何已寫入流中的數據(不回退),並且StreamWriter
仍可能有數據緩沖(不刷新)。 那是一個問題。
接下來,在不刷新StreamWriter
情況下檢查“極限”,這意味着可能還有更多數據,這意味着您應該壓縮,但不是。 因此,我建議您在if
語句完全出現之前調用sw.Flush()
。
最后,我強烈建議不要無緣無故創建另一個字節數組-您最終的using
語句的主體可以是:
stream.CopyTo(file);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.