Search code examples
c#uwpopenxmlwindows-10-universalopenxml-sdk

Not able to access the Word Document on my system using the UWP application


I am trying to edit a existing Word document using the UWP app (Universal Windows). But for some reason I am getting "File does not exist" error.

I have tried using the below code to access the word document:

using(WordprocessingDocument wordDoc = WordprocessingDocument.Open("C:\\Users\\Public\\Desktop\\Doc1.docx", true))
{

}

System.IO.FileNotFoundException: 'Could not find document'


Solution

  • Based on further clarification in the comments section, please see the following instructions.

    1. Add your .DOCX file to the Assets folder within your project and set the build action to "Content".

      Set Build action to Content

    2. In order to write any changes to the file, we'll need to copy it to the packages LocalFolder and then access it from there.

      var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/doc1.docx"));
      if (file != null)
      {
          //Copy .docx file to LocalFolder so we can write to it
          await file.CopyAsync(ApplicationData.Current.LocalFolder);
          String newFile = ApplicationData.Current.LocalFolder.Path + "/doc1.docx";
      
          using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(newFile, true))
          {
                  //Your code here
          }
      }
      

    You'll need to expand on this somewhat to make sure the file is only copied to the LocalFolder once etc, but you get the basic idea.