Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a string into a FileStream without going to disk?

Tags:

string abc = "This is a string"; 

How do I load abc into a FileStream?

FileStream input = new FileStream(.....); 
like image 676
Mennan Avatar asked Jan 17 '12 16:01

Mennan


People also ask

How do I write a memory stream file?

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.

What is the difference between MemoryStream and FileStream?

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.

How do I view a FileStream file?

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.

How does FileStream work C#?

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.


1 Answers

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")

like image 130
musefan Avatar answered Sep 20 '22 05:09

musefan