Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to filestream in c#

Just started with writing unit tests and I am now, blocked with this situation:

I have a method which has a FileStream object and I am trying to pass a "string" to it. So, I would like to convert my string to FileStream and I am doing this:

File.WriteAllText(string.Concat(Environment.ExpandEnvironmentVariables("%temp%"),   
 @"/test.txt"), testFileContent); //writes my string to a temp file!


new FileStream(string.Concat(Environment.ExpandEnvironmentVariables("%temp%"),  
    @"/test.txt"), FileMode.Open) //open that temp file and uses it as a fileStream!

close the file then!

But, I guess there must be some very simple alternative to convert a string to a fileStream.

Suggestions are welcome! [Note there are other answers to this question in stackoverflow but none seems to be a straight forward solution to that]

Thanks in advance!

like image 596
now he who must not be named. Avatar asked Jul 24 '13 11:07

now he who must not be named.


People also ask

Can we convert string to stream?

We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class.

How do I use FileStream?

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.

What is stream and FileStream?

Stream is a representation of bytes. Both these classes derive from the Stream class which is abstract by definition. 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.


1 Answers

First of all change your method to allow Stream instead of FileStream. FileStream is an implementation which, as I remember, does not add any methods or properties, just implement abstract class Stream. And then using below code you can convert string to Stream:

public Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}
like image 73
Piotr Stapp Avatar answered Sep 27 '22 20:09

Piotr Stapp