Reputation: 868
How can I create an html file in memory given some text,then name the file, create its content type then put it in a stream without writing to the device, I would just need the stream.
I am sending the content as a byte[]
to a web service.
I could use something like this, but i do not want to actually have a physical file but instead just the stream so that i can convert to its byte representation and send it, I do not have a path either.. just not sure how to go about this
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true)
.GetBytes("<html><p>Some test to save in mycontent.html</p></html>");
fs.Write(info, 0, info.Length); //i do not want to generate the file
}
I want the stream to know that the file name is named mycontent.html
, content type text/html
and the content to be in stream format or byte[]
.
Upvotes: 1
Views: 606
Reputation: 684
As soon as you leave the using block’s scope, the stream is closed and disposed. The Close() calls the Flush(). Flush() is exactly what you want to avoid.
Try overriding the Flush() so it does nothing when called.
public class MyStream : FileStream
{
public override void Flush()
{
//Do nothing
reutrn;
}
}
Upvotes: -1
Reputation: 28499
Just use a MemoryStream
using (MemoryStream mem = new MemoryStream())
{
// Write to stream
mem.Write(...);
// Go back to beginning of stream
mem.Position = 0;
// Use stream to send data to Web Service
}
Upvotes: 1
Reputation: 118977
Don't use a FileStream
, instead use a MemoryStream
. For example:
using (var ms = new MemoryStream())
{
Byte[] info = new UTF8Encoding(true).GetBytes("<html><p>Some test to save in mycontent.html</p></html>");
ms.Write(info, 0, info.Length);
ms.Position = 0;
//Do something with your stream here
}
Note that no stream "knows" what the file name is going to be. You set that metadata as part of the process you use to send it to the client.
Upvotes: 3