Invalid Hyperlink: Malformed URI is embedded as a hyperlink in the document

后端 未结 1 1035
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-08 06:40

I\'m using the OpenXml namespace in my application. I\'m using this to read the XML within an Excel file. This works fine with certain excel files but on others I get a run time

1条回答
  •  无人及你
    2021-02-08 07:14

    Solution is from Eric White's blog post


    1. Import OpenXmlPowerTools from Nuget and use it.

      using OpenXmlPowerTools;
      

      The method needed is OpenXmlPowerTools.UriFixer.FixInvalidUri, or you could copy the UriFixer class from the link.


    1. Add the FixUri() Function to handle the broken URI's with a new defined URI.

      private static Uri FixUri(string brokenUri)
      {
          return new Uri("http://broken-link/");
      }
      

    1. Add code to open the document, if the exception occurs it fixes the URI's and re-opens the fixed document.

      WordprocessingDocument wDoc;
      try
      {
          using (wDoc = WordprocessingDocument.Open(newFileName, true))
          {
              //Try do something
          }
      }
      catch (OpenXmlPackageException e)
      {
          if (e.ToString().Contains("Invalid Hyperlink"))
          {
              using (FileStream fs = new FileStream(newFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
              {
                  //Fix problematic URI's
                  UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri));
              }
              using (wDoc = WordprocessingDocument.Open(newFileName, true))
              {
                  //Do something without error
              }
          }
      }
      

    0 讨论(0)
提交回复
热议问题