The specified package is not valid. The main part is missing

Below is the merge function, which is designed to merge all docx files into a folder and create a merged file.

public  void Merge()
{  
    try
    {

        string sid = Request.QueryString["studid"];
        string stud = sid.ToString();

        string ds = HttpContext.Current.Server.MapPath(("~\\StudentBinder") + "\\Temp4\\");
        if (Directory.Exists(ds))
        {
            DirectoryInfo d = new DirectoryInfo(ds);
            FileInfo[] Files = d.GetFiles("*" + stud + "*.docx");

              // stud added for differentiating b/w users

            string[] filepaths = new string[Files.Length];
            int index = 0;

            foreach (FileInfo file in Files)
            {
                filepaths[index] = file.Name;
                index++;
            }


                using (WordprocessingDocument myDoc = WordprocessingDocument.Open(Server.MapPath(filepaths[0]), true))

                {
                    for (int i = 1; i < filepaths.Length; i++)
                    {
                        MainDocumentPart mainPart = myDoc.MainDocumentPart;
                        string altChunkId = "AltChunkId" + i.ToString();
                        AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                        using (FileStream fileStream = File.Open(@filepaths[i], FileMode.Open))
                        {
                            chunk.FeedData(fileStream);
                        }
                        AltChunk altChunk = new AltChunk();
                        altChunk.Id = altChunkId;
                        mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
                        mainPart.Document.Save();
                        myDoc.Close();
                    }
                }
        }
    }
    catch (Exception ex)
    {
    }
}

but the line

using (WordprocessingDocument myDoc = WordprocessingDocument.Open(Server.MapPath(filepaths[0]), true))

causes an error. The specified package is invalid. The main part is missing.

I do not know what is wrong with this statement. Any suggestions are welcome. Thanks in advance.

+4
source share
1 answer

You are probably using Server.MapPath twice: at the beginning

string ds = HttpContext.Current.Server.MapPath(("~\\StudentBinder")+"\\Temp4\\")

and in line

using (WordprocessingDocument myDoc = WordprocessingDocument.Open(Server.MapPath(filepaths[0]), true))

You can rewrite this line as

using (WordprocessingDocument myDoc = WordprocessingDocument.Open(filepaths[0], true))

and you also need to populate an array of file arrays from the file. FullName, not file.Name:

foreach (FileInfo file in Files)
{
    filepaths[index] = file.FullName;
    index++;
}
+2
source

Source: https://habr.com/ru/post/1666882/


All Articles