尝试使用OpenXML打开复制的word doc时访问被拒绝

时间:2013-10-14 18:05:02

标签: c# openxml mailmerge

我正在尝试使用c#,DataSet和OpenXML自动化邮件合并过程。我在本地运行时有一个完整的工作示例。然而,当我们发布到我们的网络服务器时,即使在任何地方都给予完全控制,我也会收到“拒绝访问”错误。

以下是导致错误消息的代码:

        try
        {
            var strTemplateTestFile = strMergeBuildingLocation.Replace(".docx", "_Test.docx");

            // Don't continue if the template file name is not found
            if (!File.Exists(strTemplateFileName))
                throw new Exception("TemplateFileName (" + strTemplateFileName + ") does not exist");

            foreach (var dr in dsData.Tables[0].Rows)
            {

                    string strFileName;

                if (doesDestinationExist(strMergeBuildingLocation))
                {
                    File.Copy(strTemplateFileName, strTemplateTestFile, true);
                    strFileName = strTemplateTestFile;
                }
                else
                {
                    File.Copy(strTemplateFileName, strMergeBuildingLocation, true);
                    strFileName = strMergeBuildingLocation;
                }

                var pkg = Package.Open(strFileName, FileMode.Open, FileAccess.ReadWrite);
                using (var docGenerated = WordprocessingDocument.Open(pkg))

尝试打开docGenerated时,问题属于最后一行。

我收到的错误消息是:

  

拒绝访问路径'docx path'。

文件按预期复制,可以手动打开和修改。文件夹中没有任何内容可以限制对文件的访问。有没有人对这个问题有什么想法?

1 个答案:

答案 0 :(得分:0)

我认为问题出在这一行。

var pkg = Package.Open(strFileName, FileMode.Open, FileAccess.ReadWrite);
            using (var docGenerated = WordprocessingDocument.Open(pkg))

在这里,您尝试打开文档两次。

试试这个,

/* Open WordProcessing document package based on filename */
    //------------------------------------------------------------------------------------------------Start
    public static WordprocessingDocument OpenPackage(WordprocessingDocument package, string inputFileName, bool editable)
    {
        bool copied = false;
        while (!copied)
        {
            try
            {
                package = WordprocessingDocument.Open(inputFileName, editable);
                copied = true;
            }
            catch (Exception e)
            {
                if (e is FileFormatException)
                {
                    package = null;
                    break;
                }
                if (e is IOException)
                {
                    copied = false;
                }
                if (e is ZipException)
                {
                    package = null;
                    break;
                }
            }
        }

        return package;
    }

如果WordprocessingDocument包存在且可用,它将为您提供。如果file不存在,则返回null。如果文件被锁定,则在文件释放时打开包。 希望这可以帮助。!谢谢!