Search code examples
c#asp.net-mvcasp.net-mvc-3filestreamdocx

DocX with filestream doesn't save


So for a project I am creating Résumé's and i need to save them into a docx file. It is a ASP.NET MVC application and for the docx generating I'm using the libray docx to create the document.

I can create the file but the filestream doesn't add the content i put into it.

Here is a the code i use

public ActionResult CVToWord(int id) 
        {
            var CV = CVDAO.CV.Single(cv => cv.id == id);
            var filename = "CV - " + CV.firstname + " " + CV.name + " - " + CV.creationdate.ToString("dd MM yyyy") + ".docx";
            System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.OpenOrCreate);

            using (DocX doc = DocX.Create(stream)) 
            {
                Paragraph title = doc.InsertParagraph();
                title.Append(CV.firstname + " " + CV.name);
                doc.Save();
            }

            return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename);
        }

Like i said, this creates the file but the file doesn't have any content. Any one have a idea why?


Solution

  • public ActionResult CVToWord(int id) 
            {
                var CV = CVDAO.CV.Single(cv => cv.id == id);
                var filename = "CV - " + CV.firstname + " " + CV.name + " - " + CV.creationdate.ToString("dd MM yyyy") + ".docx";
    
                using (DocX doc = DocX.Create(filename)) 
                {
                    Paragraph title = doc.InsertParagraph();
                    title.Append(CV.firstname + " " + CV.name);
                    doc.Save();
                }
    
                System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);
                return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename);
            }
    

    This works