[英]Creating text file using stream but not writing to disk
如何在給定文本的情況下在內存中創建html文件,然后命名該文件,創建其內容類型,然后將其放入流中而不寫入設備,我只需要該流。
我正在將內容作為byte[]
發送到Web服務。
我可以使用類似這樣的東西,但是我實際上並不希望擁有物理文件,而是僅擁有流,以便我可以轉換為其字節表示形式並發送它,我也沒有路徑..只是不確定如何去這個
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true)
.GetBytes("<html><p>Some test to save in mycontent.html</p></html>");
fs.Write(info, 0, info.Length); //i do not want to generate the file
}
我想讓流知道該文件名名為mycontent.html
,內容類型為text/html
並且該內容采用流格式或byte[]
。
不要使用FileStream
,而是使用MemoryStream
。 例如:
using (var ms = new MemoryStream())
{
Byte[] info = new UTF8Encoding(true).GetBytes("<html><p>Some test to save in mycontent.html</p></html>");
ms.Write(info, 0, info.Length);
ms.Position = 0;
//Do something with your stream here
}
請注意,沒有流“知道”文件名。 您將該元數據設置為用於將其發送到客戶端的過程的一部分。
只需使用MemoryStream
using (MemoryStream mem = new MemoryStream())
{
// Write to stream
mem.Write(...);
// Go back to beginning of stream
mem.Position = 0;
// Use stream to send data to Web Service
}
一旦離開了using塊的作用域,流就被關閉並處置。 Close()調用Flush()。 Flush()正是您要避免的。
嘗試覆蓋Flush(),以便在調用時不執行任何操作。
public class MyStream : FileStream
{
public override void Flush()
{
//Do nothing
reutrn;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.