Convert string to filestream in C #

It just started by writing unit tests, and now I'm blocked by this situation:

I have a method that has a FileStream object, and I'm trying to pass a string to it. So, I would like to convert my string to a FileStream, and I do 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!

But, I think there should be some very simple alternative to converting a string to a Stream file.

Suggestions are welcome! [Note that there are other answers to this question in stackoverflow, but none of them are a direct solution to this]

Thanks in advance!

+4
source share
2 answers

First of all, change your method to allow Stream instead of FileStream . FileStream is an implementation that, as I recall, does not add any methods or properties, it simply implements the abstract Stream class. And then, using the code below, 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; } 
+10
source

As a class, the FileStream class provides a stream for a file, and therefore its constructor requires a path to the file, mode, permission parameter, etc. to read the file into the stream and, therefore, it is used to read text from the file to the stream. If we need to convert a string to a stream first, we need to convert the string to an array of bytes, since the stream is a sequence of bytes. Below is the code.

  //Stream is a base class it holds the reference of MemoryStream Stream stream = new MemoryStream(); String strText = "This is a String that needs to beconvert in stream"; byte[] byteArray = Encoding.UTF8.GetBytes(strText); stream.Write(byteArray, 0, byteArray.Length); //set the position at the beginning. stream.Position = 0; using (StreamReader sr = new StreamReader(stream)) { string strData; while ((strData= sr.ReadLine()) != null) { Console.WriteLine(strData); } } 
0
source

Source: https://habr.com/ru/post/1493176/


All Articles