C# 使用FileStream复制Word文档会损坏文档
我正在编写一个WCF服务,它使用字节缓冲区传输大文件。我对Word docx有问题。我可以复制文件,但当我打开它时,会出现“文件损坏”错误,然后它会询问我是否要修复它。如果我说“是的”,它可以挽救它 如何复制word文档?我试着改变了编码方式,在网上我能找到的一切都没有用 这是我的客户:C# 使用FileStream复制Word文档会损坏文档,c#,wcf,ms-word,C#,Wcf,Ms Word,我正在编写一个WCF服务,它使用字节缓冲区传输大文件。我对Word docx有问题。我可以复制文件,但当我打开它时,会出现“文件损坏”错误,然后它会询问我是否要修复它。如果我说“是的”,它可以挽救它 如何复制word文档?我试着改变了编码方式,在网上我能找到的一切都没有用 这是我的客户: FileInfo SourceFile = new FileInfo(textBoxPath.Text); LargeFileContractClient localClient = new LargeFile
FileInfo SourceFile = new FileInfo(textBoxPath.Text);
LargeFileContractClient localClient = new LargeFileContractClient();
LargeFileInfo LocalLargeFileInfo = new LargeFileInfo();
LocalLargeFileInfo.TransactionID = Guid.NewGuid();
LocalLargeFileInfo.FileName = SourceFile.Name;
LargeFileInfo localLargeFileResponse = new LargeFileInfo();
using (BinaryReader SourceStream = new BinaryReader(File.Open(SourceFile.FullName, FileMode.Open), Encoding.Unicode))
{
while (SourceStream.BaseStream.Position < SourceStream.BaseStream.Length)
{
//Get a set of bytes and pack them into the largefileinfo
int BytesRead = SourceStream.Read(FileBuffer, 0, 1000);
LocalLargeFileInfo.FileContent = FileBuffer;
//Send the LargeFileInfo to the server
localLargeFileResponse = localClient.TransferLargeFile(LocalLargeFileInfo);
}
}
我试过改变编码。我尝试过使用普通文件流。我已经尝试了我能想到的一切,但我无法打开最后的文件
我可以复制ZIP、AutoCAD dwg和PDF,但不能复制Word文档。它们有什么特别之处?您是否检查过以确保没有任何数据可供参考?您使用的是
FileMode.Append
(我假设您可以将文件分为多个块传输),但我没有看到一个检查,以确保您没有通过附加到已存在的内容来创建垃圾文件。我错过了根据传入的GUID创建新目录的部分。所以,不,那里没有文件。让我困惑的是.docx实际上是.zip的一种特殊形式。您可以更改扩展名并将其作为.zip打开。也许可以尝试将其转换为.zip,传输它,然后将其重新命名为.docx?这将确保问题不在文件名中,尽管这是一个长期问题。等等,您使用的是BinaryReader
。这是针对基本类型的。试着改用File.ReadAllBytes
(或者File.OpenRead
,如果你是成批地这样做的话)BinaryReader只是最新的咒语。我尝试了File.OpenRead(),它也做了同样的事情。我将尝试一下zip建议,看看会发生什么。
public LargeFileInfo TransferLargeFile(LargeFileInfo argFileInfo)
{
FileInfo DestFile = new FileInfo(String.Format(@"C:\LargeFiles\{0}\{1}", argFileInfo.TransactionID, argFileInfo.FileName));
if(!DestFile.Directory.Exists)
{
DestFile.Directory.Create();
}
using (BinaryWriter DestStream = new BinaryWriter(new FileStream (DestFile.FullName, FileMode.Append), Encoding.Unicode))
{
DestStream.Write(argFileInfo.FileContent, 0, argFileInfo.FileContent.Length);
}
argFileInfo.ContinueFrom += argFileInfo.FileContent.Length;
return argFileInfo;
}