[英]Directly read a byte document with FileStream (without path)
我在變量中有一個字節文檔,我想將其放入FileStream
以便在StreamReader
使用它。
我可以這樣做嗎?
我看到FileStream
使用路徑,但是有沒有辦法讀取我的字節文檔?
我得到了這樣的東西,當然, myByteDocument
不起作用,因為它不是路徑:
file = new FileStream(myByteDocument, FileMode.Open, FileAccess.Read, FileShare.Read);
reader= new StreamReader(file);
reader.BaseStream.Seek(0, SeekOrigin.Begin);
string fullText= "";
while (reader.Peek() > -1)
{
fullText+= reader.ReadLine();
}
reader.Close();
myByteDocument是這樣獲得的:
DataRow row = vDs.Tables[0].Rows
byte[] myByteDocument = (byte[])row.ItemArray[0];
我閱讀了文檔,然后將其放入字符串中進行替換,然后替換掉所有部分,然后創建一個帶有fullText
變量的新文檔,其中包含sw.write(fullText)
,其中sw
是一個StreamWriter
。
因此,我想在不知道路徑的情況下讀取文件,而是直接使用字節文檔。 我可以這樣做嗎?
如果我不清楚,請不要猶豫。
您應該查看MemoryStream
類而不是FileStream
。 它應該提供在不知道路徑的情況下讀取文件所需的功能(假設myByteDocument
是字節數組)。
var file = new MemoryStream(myByteDocument);
您基本上可以使用相同的代碼,只需將MemoryStream構造函數替換為您嘗試使用的FileStream構造函數。
string fullText= "";
using(var file = new MemoryStream(myByteDocument))
using(var reader = new StreamReader(file))
{
reader.BaseStream.Seek(0, SeekOrigin.Begin);
while (!reader.EndOfStream)
{
fullText += reader.ReadLine();
}
}
請注意,我還添加了using
塊用於文件訪問。 這比只調用reader.Close()
更可取,因為即使在沒有調用Close()
方法的情況下發生異常,也可以確保清除資源。
您需要的是將字節數組轉換為字符串,然后替換所需的內容並寫入最終結果。 您甚至不需要StreamReaders或writer來執行此操作。
看一下這篇文章: 如何將byte []轉換為字符串?
在這里,您可以使用不同的方法將文檔轉換為字符串。 可以接受的答案是:
string result = System.Text.Encoding.UTF8.GetString(myByteDocument)
完成所有替換操作后,只需將字符串保存到文件中,即可(最簡單的方法):
File.WriteAllText(path, result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.