指定Office文档加载程序集的绝对路径

     使用VSTO进行Office开发时,默认情况下生成的文件和你的程序集必须在一起才能正确使用,也就是说文档是根据相对路径来寻找程序集的,如何改变这种状况,使得我们可以把Office文档拷贝到任意地方又不影响文档加载程序集呢?最稳妥的办法是把程序集保存到GAC中,这样发布给用户使用时,用户可以不关心程序集的位置。 还有没有其他方式呢?
     Msdn是这样说明的: 在加载文档时,Excel 2003 和 Word 2003 会检查文档中的两个自定义属性:_AssemblyLocation0_AssemblyName0。如果找到这些属性,宿主应用程序会加载 Visual Studio Tools for the Microsoft Office System 程序集加载程序 (Otkloadr.dll)。这个未托管的 DLL 负责加载使用 Visual Studio Tools for the Microsoft Office System 创建的程序集。该加载程序使用文档的自定义属性查找该文档的程序集、将该程序集加载到内存、检查某些元数据、建立宿主和程序集之间的引用,然后结束其操作。
       _AssemblyLocation0 这个属性保存的就是程序集的相对路径,只要我们在保存文档时,只要把_AssemblyLocation0 这个属性的相对路径改为绝对路径,就可以把文档拷贝到你机器的任何地方,而不用每次都必须连带程序集一起拷贝了。
        示例代码,我的Word模板工程是这样处理的:
     
Microsoft.Office.Core.DocumentProperties properties =
                (Microsoft.Office.Core.DocumentProperties)
                m_wordDocument.CustomDocumentProperties;
            Microsoft.Office.Core.DocumentProperty pathProperty 
=
                properties[
"_AssemblyLocation0"];

            
string firstLocationFragment = (string)pathProperty.Value;
            
if (System.IO.Path.IsPathRooted(firstLocationFragment) ||
                firstLocationFragment.StartsWith(
"http://"||
                firstLocationFragment.StartsWith(
"https://"||
                firstLocationFragment.StartsWith(
"file://")
                )
            
{
                
return;
            }


            
string documentFolder = ((Word.Template)m_wordDocument.get_AttachedTemplate()).Path;

            
string longPath = System.IO.Path.Combine(documentFolder, firstLocationFragment);
            
string absolutePath = System.IO.Path.GetFullPath(longPath);
            pathProperty.Value 
= absolutePath;

posted on 2005-03-18 16:20  mist  阅读(1189)  评论(0编辑  收藏  举报

导航