locked
Word Document Corrupted After Posting to Controller RRS feed

  • Question

  • User-868767480 posted

    Evening,

    I appreciate everybody input and patience this is my third week learning C# and ASP, so still a green horn, but I'm learning.

    So i can post the file and save the file but when i open the file in word it tells me that it is Word Found Unreadable Content do you want to recover the file Yes, No.

    I've trawled the internet and found a few solutions I have focused on these two but I'm still stuck any help would be awesome.

    Thanks

    Madaxe

    //Method1
    byte[] HttpPostedDocumentFileData = new byte[HttpPostedDocumentFile.InputStream.Length];
    File.WriteAllBytes(Path.Combine(path, VaultFileName), HttpPostedDocumentFileData);
    
    //Method2
    HttpPostedDocumentFile.SaveAs(Path.Combine(path, VaultFileName));

    //https://localhost:44360/api/OfficeAddin/StreamDocument
            [HttpPost]//[Route("StreamDocument")]
            public IHttpActionResult StreamDocument()
            {
                HttpRequest HttpRequest = HttpContext.Current.Request;
                if (HttpRequest.Files.Count == 2)
                {
                    //Get The Two Files by Key
                    HttpPostedFile HttpPostedDocumentFile = HttpRequest.Files.Get("Document");
                    HttpPostedFile HttpPostedXMLFile = HttpRequest.Files.Get("XMLFile");
    
                    if (HttpPostedXMLFile != null)
                    {
                        XDocument XMLRegistrationFile = XMLHelper.DecodeInputStream(HttpPostedXMLFile.InputStream);
    
                        string VaultID = XMLRegistrationFile.Descendants("OfficeAddinModel").ElementAt(0).Descendants("VaultID").ElementAt(0).Value;
                        string VaultFileName = XMLRegistrationFile.Descendants("OfficeAddinModel").ElementAt(0).Descendants("VaultFileName").ElementAt(0).Value;
    
                        if (HttpPostedDocumentFile != null)
                        {
                            string path = HttpContext.Current.Server.MapPath(Path.Combine("~/Uploads/", VaultID));
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            try
                            {
                                //Method1
                                byte[] HttpPostedDocumentFileData = new byte[HttpPostedDocumentFile.InputStream.Length];
                                File.WriteAllBytes(Path.Combine(path, VaultFileName), HttpPostedDocumentFileData);
    
                                //Method2
                                HttpPostedDocumentFile.SaveAs(Path.Combine(path, VaultFileName));
                                return Ok();
                            }
                            catch (Exception ex)
                            {
                                return InternalServerError(new Exception(ex.Message.ToString()));
                            }
                        }
                        else
                        {
                            return InternalServerError(new Exception("The Application Document File Was Null."));
                        }
                    }
                    else
                    {
                        return InternalServerError(new Exception("The XML Document File Was Null."));
                    }
                }
                else
                {
                    return InternalServerError(new Exception("The File Count Was Not Equal to Two."));
                }
            }

    Tuesday, December 10, 2019 9:13 PM

All replies

  • User475983607 posted

    How are you currently uploading the documents?  Are you using HTTP multipart form?  

    I would use HttpClient and you can include the file name in the HTTP message. 

    https://blogs.msdn.microsoft.com/wsdevsol/2014/03/25/httpclient-and-empty-items-in-a-multipart-form-post/

    Tuesday, December 10, 2019 9:29 PM
  • User-868767480 posted

    Thanks for the response here is the client side code for the word addin

    public static Boolean StreamFileToVault(string iURL, Document iDocument)
            {
                LogHelper.Log(LogTarget.File, LogSeverity.Information, "Start_StreamFileToVault.");
                Boolean ReturnBoolean = false;
                try
                {
                    Dictionary<string, string> FileUploadDictionary = new Dictionary<string, string>();
                    FileUploadDictionary.Add("Document", iDocument.FullName);
                    FileUploadDictionary.Add("XMLFile", Path.Combine(iDocument.Path, Path.GetFileNameWithoutExtension(iDocument.FullName)) + ".xml");
    
                    using (HttpClient client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.BaseAddress = new Uri(WordAddinImplementation._BaseAddress);
    
                        using (MultipartFormDataContent content = new MultipartFormDataContent())
                        {
                            foreach (KeyValuePair<string, string> iItem in FileUploadDictionary)
                            {
                                WordAddinImplementation.AddFileContent(iItem.Key.ToString(), FileUploadDictionary[iItem.Key], content);
                            }
    
                            HttpResponseMessage response = client.PostAsync(iURL, content).Result;
    
                            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                ReturnBoolean = true;
                            }
                        }
                    }
                    LogHelper.Log(LogTarget.File, LogSeverity.Information, "End_StreamFileToVault.");
                }
                catch (Exception ex)
                {
                    throw new Exception("Webservice Failed to Stream File to Vault", ex);
                }
                return ReturnBoolean;
            }
    private static void AddFileContent(string iKey,string iFilePath, MultipartFormDataContent iContent)
            {
                FileStream DocFileStream = new FileStream(iFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    
                byte[] Bytes = new byte[DocFileStream.Length + 1];
                DocFileStream.Read(Bytes, 0, Bytes.Length);
    
                //"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    
                ByteArrayContent fileContent = new ByteArrayContent(Bytes);
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = iKey };
                if (iKey == "Document")
                {
                    //fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(Path.GetFileName(iFilePath)));
    } iContent.Add(fileContent); }

    Wednesday, December 11, 2019 6:29 PM
  • User665608656 posted

    Hi madaxe,

    According to your description, please confirm whether the word document can be successfully opened before you upload it?

    Usually when a word file becomes corrupted and its contents become unreadable, you may encounter the "Word found unreadable content" issue.

    You can refer to this for more information : Word found unreadable content...

    Is HttpPostedDocumentFile your custom class in your code?

    I cannot successfully test your code because your code does not provide comprehensive information, but you can refer to this link to try to change the way to save the file:

    https://stackoverflow.com/a/37291210

    Upload files in ASP.NET Core

    Best Regards,

    YongQing.

    Friday, December 13, 2019 3:05 AM
  • User-868767480 posted

    the file is created through the word api or by the user and is fine prior to uploading. I will check out your link to see if i can find  a resolution

    thanks

    Madaxe

    Friday, December 13, 2019 5:57 AM