My ultimate goal is to upload an rtf document and store the binary contents in a table, then retrieve the contents of that template, replace some text based on some pre-defined tags, and trigger the browser to download the updated template. My initial goal is to upload a rtf file (working), run it through my parsing method (with no changes), and have the downloaded file open successfully with the original template. Right now everything below is working, except the file produced is corrupt (and I'm not sure that my streams are being disposed of properly). I should probably dig into System.IO to better understand memory streams, etc., but this is the only place in this project where I need to do anything like this, so I'm trying to find a quick solution.
public static Stream ParseFile(Stream fsTemplate)
{
// create MemoryStream to copy template into and modify as needed
MemoryStream doc = new MemoryStream();
// copy template FileStream into document MemoryStream
fsTemplate.CopyTo(doc);
doc.Position = 0;
string docText = string.Empty;
using (StreamReader reader = new StreamReader(doc))
{
// doctText appears to look how I'd expect when I debug
docText = reader.ReadToEnd();
reader.Close();
}
//replace text in 'docText' as neccessary (not yet implemented)
// This is where I'm not really clear what I should be doing differently
var ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms);
writer.Write(docText);
ms.Position = 0;
return ms;
}
Here's my controller, which retrieves binary data (uploaded rtf template) from the database, calls the above method, and returns the file stream to the browser
public FileStreamResult Parse(int id)
{
byte[] data = Context.Templates.Find(id).BinaryData;
Stream stream = new MemoryStream(data);
var updatedStream = Tools.ParseFile(stream);
return File(updatedStream, "application/rtf", "temp.rtf");
}
I replaced my StreamWriter with this block of code, and now it's working how I expected. I'm still not sure if I'm disposing of my streams properly though.
byte[] buffer = Encoding.ASCII.GetBytes(docText);
MemoryStream ms = new MemoryStream(buffer);
Full code:
public static Stream ParseFile(Stream fsTemplate)
{
// create MemoryStream to copy template into and modify as needed
MemoryStream doc = new MemoryStream();
// copy template FileStream into document MemoryStream
fsTemplate.CopyTo(doc);
doc.Position = 0;
string docText = string.Empty;
using (StreamReader reader = new StreamReader(doc))
{
// doctText appears to look how I'd expect when I debug
docText = reader.ReadToEnd();
reader.Close();
}
//replace text in 'docText' as neccessary (not yet implemented)
byte[] buffer = Encoding.ASCII.GetBytes(docText);
MemoryStream ms = new MemoryStream(buffer);
return ms;
}