简体   繁体   中英

Directly read a byte document with FileStream (without path)

I have a byte document in a variable, and I want to put it into a FileStream for using it into a StreamReader .

Can I do this?

I saw that FileStream uses a path, but is there a way to read my byte document?

I got something like this, of course, the myByteDocument doesn't work, because it's not a path:

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 is obtain like this :

DataRow row = vDs.Tables[0].Rows
byte[] myByteDocument = (byte[])row.ItemArray[0];

I read the document, and put it into a string to replace, some pieces of it, and then after all the replace, I create a new document with the fullText variable, with something like sw.write(fullText) , where sw is a StreamWriter .

So, I want to read the file, without knowing the path, but with the byte document directly. Can I do this?

If I'm not clear, don't hesitate, say it.

You should look at the MemoryStream class instead of FileStream . It should provide the functionality you need to read the file without knowing the path (provided myByteDocument is a byte array).

var file = new MemoryStream(myByteDocument);

You can basically use your same code just substituting the MemoryStream constructor for the FileStream constructor you were trying to use.

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();
    }
}

Please note, I also added using blocks for the file access. This is much preferable to just calling reader.Close() as it will ensure the cleanup of the resources even if an Exception occurs where just calling the Close() method will not.

What you need is convert your byte array to string, then replace what you need, and write the final result. You don't even need StreamReaders or writers to do this.

Take a look at this post: How to convert byte[] to string?

Here you have different methods to convert your document to a string. The one accepted as an answer is:

string result = System.Text.Encoding.UTF8.GetString(myByteDocument)

Once you've done all your replacements, just save the string into a file, with something like that (most simple way):

File.WriteAllText(path, result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM