I am trying to convert a docx file to a pdf. I am using code from stackoverflow, but modified to allow for the dynamic selection of a file to open (rather than a hard-coded value). When I run it, I get an exception on the Open() method - could not find file. I select the file using a fileupload control so I know the file is there. What's going on?
Here is my code:
using System;
using System.IO;
using Microsoft.Office.Interop.Word;
using OpenXmlPowerTools;
namespace DocxToPdf
{
public partial class WebForm1 : System.Web.UI.Page
{
public Microsoft.Office.Interop.Word.Document wordDoc;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (DocxFileUpload.HasFile)
{
string docxFile = DocxFileUpload.PostedFile.FileName;
FileInfo fiFile = new FileInfo(docxFile);
if (Util.IsWordprocessingML(fiFile.Extension))
{
Guid pdfFileGuid = Guid.NewGuid();
string pdfFileLoc = string.Format(@"c:\windows\temp\{0}.pdf", pdfFileGuid.ToString());
Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
wordDoc = appWord.Documents.Open(docxFile);
wordDoc.ExportAsFixedFormat(pdfFileLoc, WdExportFormat.wdExportFormatPDF);
MsgLabel.Text = "File converted to PDF";
}
else
{
MsgLabel.Text = "Not a WordProcessingML document.";
}
}
else
{
MsgLabel.Text = "You have not specified a file.";
}
}
}
}
The error occurs on the "wordDoc = appWord.Documents.Open(docxFile);" line.
The fileupload control FileName property has just the file name, not the fully qualified path. I understand why I'm getting a "file not found" error - it's because the file doesn't have the fully qualified path in it. My question to the group is, how do I get the fully qualified path and file name, so I can open it? I've run a debug session and examined all the properties of the fileupload control and the FileInfo control, but they don't have it. The "FullPath" property of the FileInfo control is set to "c:\Program Files (x86)\IIS Express\myfile.docx", but that's not where the file is located.
Here's some more information about the error: Exception System.Runtime.InteropServices.COMException in DocxToPdf.dll (Sorry, we couldn't find your file. Is it possible it was moved, renamed or deleted? C:\Windows...\myfile.docx...
I've googled around on this, but so far no luck. Please help! Thanks.