此代码(chunk.feeddata)返回流不可读错误。我不知道为什么会发生。文件具有所有权限。有没有办法解决它。欢迎所有建议。代码只是尝试将第一个文件复制到输出文件,然后将下一个文件追加到输出文件的末尾。
public void Merge()
{
try
{
string Temps = Server.MapPath(...); //create folder
if (!Directory.Exists(Temps))
{
Directory.CreateDirectory(Temps);
}
string output = Path.Combine(Temps + ....+ ".doc");
string sid = Request.QueryString["id"];
string stud = sid.ToString();
string ds = HttpContext.Current.Request.MapPath(......);
DirectoryInfo dinfo = new DirectoryInfo(ds);
DirectorySecurity dSecurity = dinfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dinfo.SetAccessControl(dSecurity);
if (Directory.Exists(ds))
{
DirectoryInfo d = new DirectoryInfo(ds);
FileInfo[] Files = d.GetFiles("*" + stud + "*.docx");
string[] filepaths = new string[Files.Length];
int index = 0;
foreach (FileInfo file in Files)
{
filepaths[index] = file.FullName;
index++;
}
File.Delete(output);
File.Copy(filepaths[0], output);
for (int i = 1; i < filepaths.Length; i++)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(output, true))
{
string altChunkId = "AltChunkId1_" + i;
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
FileStream fileStream = File.Open(@filepaths[i], FileMode.Append);
{
chunk.FeedData(fileStream);
}
DocumentFormat.OpenXml.Wordprocessing.AltChunk altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
altChunk.Id = altChunkId;
mainPart.Document
.Body
.InsertAfter(altChunk, mainPart.Document.Body
.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
mainPart.Document.Save();
if(fileStream!=null)
fileStream.Dispose();
}
}
}
}
catch (Exception ex)
{
}
}
答案 0 :(得分:0)
https://www.codeproject.com/Articles/7582/Merging-Word-Documents-with-C
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileAppending
{
class Program
{
static void Main(string[] args)
{
string[] doc1 = File.ReadAllLines("C:\\FileAppending\\FileAppending\\Doc1.Docx");
string[] doc2 = File.ReadAllLines("C:\\FileAppending\\FileAppending\\Doc2.Docx");
File.WriteAllLines("C:\\FileAppending\\FileAppending\\Doc3.Docx", doc1);
File.AppendAllLines("C:\\FileAppending\\FileAppending\\Doc3.Docx", doc2);
}
}
}
答案 1 :(得分:-1)
我认为文件末尾的所有文件都有EOF(文件结尾)标记。可能这是没有附加的原因。