I am using Spire.doc for creating a Word file, and I followed their example like this
public class WordController : Controller
{
public void Download()
{
Document doc = new Document();
Paragraph test = doc.AddSection().AddParagraph();
test.AppendText("This is a test");
doc.SaveToFile("Doc.doc");
try
{
System.Diagnostics.Process.Start("Doc.doc");
}catch(Exception)
{
}
}
}
This opens the Word file in Microsoft Word, but how can I make it so that it's downloaded instead?
I've used return File()
to return a PDF document to the View before, but it doesn't work with this.
Could you please try the below code and let me know if it worked or not, cos I didn't executed this code but believe this should work, I modified my existing working code according to your requirement-
public class WordController : Controller
{
public void Download()
{
byte[] toArray = null;
Document doc = new Document();
Paragraph test = doc.AddSection().AddParagraph();
test.AppendText("This is a test");
using (MemoryStream ms1 = new MemoryStream())
{
doc.SaveToStream(ms1, FileFormat.Doc);
//save to byte array
toArray = ms1.ToArray();
}
//Write it back to the client
Response.ContentType = "application/msword";
Response.AddHeader("content-disposition", "attachment; filename=Doc.doc");
Response.BinaryWrite(toArray);
Response.Flush();
Response.End();
}
}