string abc = "This is a string";
How do I load abc into a FileStream?
FileStream input = new FileStream(.....);
One solution to that is to create the MemoryStream from the byte array - the following code assumes you won't then write to that stream. MemoryStream ms = new MemoryStream(bytes, writable: false); My research (below) shows that the internal buffer is the same byte array as you pass it, so it should save memory.
As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.
C# FileStream read text with StreamReader using FileStream fs = File. OpenRead(fileName); using var sr = new StreamReader(fs); We pass the FileStream to the StreamReader . If we do not explicitly specify the encoding, the default UTF8 is used.
The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.
Use a MemoryStream instead...
MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(abc));
remember a MemoryStream (just like a FileStream) needs to be closed when you have finished with it. You can always place your code in a using block to make this easier...
using(MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(abc))) { //use the stream here and don't worry about needing to close it }
NOTE: If your string is Unicode rather than ASCII you may want to specify this when converting to a Byte array. Basically, a Unicode character takes up 2 bytes instead of 1. Padding will be added if needed (e.g. 0x00 0x61
= "a" in unicode, where as in ASCII 0x61
= "a")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With