andrewlocatelliwoodcock

Thoughts on Software

How to create a FileStreamResult from a string

leave a comment »


I’ll return to my encryption posts shortly but in the meantime I just wanted to share a useful technique that allows you to return a string in FileStreamResult object from a Controller. The first step is to create a MemoryStream object and then use this to instantiate a FileStreamResult object.

So, to create a MemoryStream object from a string:

        public static MemoryStream StringToMemoryStream(Encoding encoding, string source)
        {
            var content = encoding.GetBytes(source);
            return new MemoryStream(content);
        }

and to use this to instantiate a FileStreamResult object:

                var mimeType = "text/plain";
                var source = "String as MemoryStream";
                var stream = StringToMemoryStream(Encoding.UTF8, source);
                var fileStreamResult = new FileStreamResult(stream, mimeType);

Written by andrewlocatelliwoodcock

July 31, 2011 at 19:41

Posted in ASP.Net MVC, C#

Tagged with , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: