none
Exception 0x800401F when using mailItem.SaveAs RRS feed

  • Question

  • I am trying to debug a VSTO that was made for Outlook. It is a simple addon that saves an email to SharePoint.

    But the users keep getting errors (Exception 0x800401F ) when saving files. I had a look at the code (it was written by a former employee)

    I tracked the error to mailItem.SaveAs(), but I still don't know the cause and how to solve it. Here is the code:

    public static void Save(Outlook.MailItem mailItem, string DocStatus, NetworkCredential myCreds, int tryCounter)
            {
                string debugString = string.Empty;
                string tmpName = string.Empty;
                try
                {
                    string fileName = UniqueName() + ".msg";
                    debugString = "Debug 01";
                    String relativeDestUrl = String.Format("{0}/{1}", MyGlobals.DocumentLibrary, fileName);
    
                    debugString = "Debug 02";
                    StringBuilder Batch = new StringBuilder(); //for webservice update
    
                    if (string.IsNullOrEmpty(DocStatus))
                        DocStatus = "Afgehandeld";
                    debugString = "Debug 03";
                    
                    if (tryCounter == 0 && mailItem.Categories != null)
                    {
                        debugString = "Debug 03.01";
                        if (mailItem.Categories.IndexOf(Category) > -1) // allready in SP??
                        {
                            debugString = "Debug 03.02";
                            if (MessageBox.Show("Dit document is reeds opgeslagen in SharePoint. Weet u zeker dat u het nog een keer wilt opslaan?", "Reeds opgeslagen", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No) return;
                        }
                    }
                    debugString = "Debug 04";
                    try
                    {
                        tmpName = System.IO.Path.GetTempFileName();
                        debugString = "Debug 05";
                        mailItem.SaveAs(tmpName, Outlook.OlSaveAsType.olMSG);
    
                        debugString = "Debug 06";
                        using (ClientContext context = new ClientContext(MyGlobals.SiteUrl))
                        {
                            debugString = "Debug 07";
                            if (MyGlobals.Authentication == MyGlobals.AuthenticationType.FBA)
                            {
                                context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
                                debugString = "Debug 08";
                                FormsAuthenticationLoginInfo formsAuthInfo = new FormsAuthenticationLoginInfo(myCreds.UserName, myCreds.Password);
                                debugString = "Debug 09";
                                context.FormsAuthenticationLoginInfo = formsAuthInfo;
                            }
                            else if (MyGlobals.Authentication == MyGlobals.AuthenticationType.NTLM)
                            {
                                debugString = "Debug 10";
                                context.AuthenticationMode = ClientAuthenticationMode.Default;
                                if (!string.IsNullOrEmpty(myCreds.UserName) && !string.IsNullOrEmpty(myCreds.Password))
                                    context.Credentials = myCreds;
                                debugString = "Debug 11";
                            }
    
                            //Get Document List
                            List documentsList = context.Web.Lists.GetByTitle("dispatch");
                            debugString = "Debug 12";
                            
                            var fileStream = new FileStream(tmpName, FileMode.Open);
                            debugString = "Filestream";
                            var byteStream = new byte[fileStream.Length];
                            debugString = "Bytestream";
                            fileStream.Read(byteStream, 0, byteStream.Length);
                            debugString = "Filestream read";
                            var fileCreationInformation = new FileCreationInformation
                            {
                                Content = byteStream,
                                Overwrite = true,
                                Url = relativeDestUrl
                            };
    
                            Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
    
                            debugString = "Debug 14";
    
                            uploadFile.ListItemAllFields["Behandelaar"] = "";// getUserId(myCreds);
                            uploadFile.ListItemAllFields["ContentTypeId"] = GetContentType(context, documentsList, MyGlobals.DefaultContentType).Id;
                            uploadFile.ListItemAllFields["Van"] = Validate(mailItem.SenderName);
                            uploadFile.ListItemAllFields["Onderwerp"] = Validate(mailItem.Subject);
                            uploadFile.ListItemAllFields["Aan"] = Validate(mailItem.To);
                            uploadFile.ListItemAllFields["BCC"] = Validate(mailItem.BCC);
                            uploadFile.ListItemAllFields["CC"] = Validate(mailItem.CC);
                            uploadFile.ListItemAllFields["Title"] = Validate(mailItem.Subject);
                            uploadFile.ListItemAllFields["Bron"] = "Mail";
                            uploadFile.ListItemAllFields["Interne_x0020_status"] = MyGlobals.DocumentStatusNew;
                            uploadFile.ListItemAllFields["Documentstatus"] = DocStatus;
                            uploadFile.ListItemAllFields.Update();
    
                            context.ExecuteQuery();
                            debugString = "Debug 15";
                            ListItem item = uploadFile.ListItemAllFields;
                            context.Load(item);
                            debugString = "Debug 16";
                            context.ExecuteQuery();
                            string itemID = item.Id.ToString();
                            debugString = "Debug 17";
                            //default setting, if closed by controlbox, annuleren is still true
                            SharePointHelper.Annuleren = true;
    
                                                  
                            OutlookAddIn.Metadata metadataForm = new OutlookAddIn.Metadata(
                                                string.Format("{0}/{1}/{2}?ID={3}&Source={4}&RootFolder={5}",
                                                MyGlobals.SiteUrl,
                                                MyGlobals.DocumentLibrary,
                                                MyGlobals.EditForm,
                                                itemID,
                                                HttpUtility.UrlEncode(string.Format("{0}/{1}/Forms/AllItems.aspx", MyGlobals.SiteUrl, MyGlobals.DocumentLibrary)),
                                                HttpUtility.UrlEncode("/Docs/Template")), myCreds);
                            metadataForm.ShowDialog();
                            debugString = "Debug 18";
    
                            if (!Annuleren)
                            {
                                //Log.Logger.Trace("OutlookAddIn: Metadata saved!");
                                try
                                {
                                    debugString = "Debug 19";
                                    context.Load(uploadFile.ListItemAllFields);
                                    context.ExecuteQuery();
                                    uploadFile.ListItemAllFields["Interne_x0020_status"] = MyGlobals.DocumentStatusFinished;
                                    uploadFile.ListItemAllFields.Update();
                                    context.ExecuteQuery();
                                    debugString = "Debug 20";
                                    //Log.Logger.Trace("OutlookAddIn: Status updated!");
    
                                    try
                                    {
                                        debugString = "Debug 21";
                                        if (mailItem.Categories == null || mailItem.Categories.IndexOf(Category) == -1)
                                            mailItem.Categories = Category + "," + mailItem.Categories;
    
                                        mailItem.Save();
                                        debugString = "Debug 22";
                                        //Log.Logger.Trace("OutlookAddIn: Outlook item updated!");
                                    }
                                    catch
                                    {
                                        //
                                    }
    
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(string.Format("Het is niet gelukt uw bericht de juiste status in Dispatch te geven. Waarschuw de systeembeheerder"), "OutLookAddIn", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    //Log.Logger.Error(ex);
                                }
                            };
                        }
                    }
                    catch (Exception ex)
                    {
                        if (tryCounter > 5)
                        {
                            if (MessageBox.Show(string.Format("Er is iets misgegaan tijdens het opslaan van uw bericht in SharePoint. Wilt u het nog een keer proberen? (Fout: {0})", tmpName + " " + debugString + " " + ex.Message), "Fout bij opslaan", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                                return;
                            else
                                Save(mailItem, DocStatus, myCreds, 0);
                        }
                        else
                        {
                            foreach (var file in Directory.GetFiles(System.IO.Path.GetTempPath().ToString()))
                            {
                                try
                                {
                                    System.IO.File.Delete(file);
                                }
                                catch
                                {
                                }
                            }
                            tryCounter++;
                            Save(mailItem, DocStatus, myCreds, tryCounter);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (tryCounter > 5)
                    {
                        if (MessageBox.Show(string.Format("Er is iets misgegaan tijdens het opslaan van uw bericht in SharePoint. Wilt u het nog een keer proberen? (Fout: {0})", tmpName + " " + debugString + " " + ex.Message), "Fout bij opslaan", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                            return;
                        else
                            Save(mailItem, DocStatus, myCreds, 0);
                    }
                    else
                    {
                        foreach (var file in Directory.GetFiles(System.IO.Path.GetTempPath().ToString()))
                        {
                            try
                            {
                                System.IO.File.Delete(file);
                            }
                            catch
                            {
                            }
                        }
                        tryCounter++;
                        Save(mailItem, DocStatus, myCreds, tryCounter);
                    }
                }
            }

    The error is after "Debug 5" (I added the debug strings, because somehow NLog is broken too).

    I thought it was because of

    foreach (var file in Directory.GetFiles(System.IO.Path.GetTempPath().ToString()))
                        {
                            try
                            {
                                System.IO.File.Delete(file);
                            }
                            catch
                            {
                            }
                        }


    But when I remove this code, users will get an "OutOfMemory Exception" whenever they try to save an email.

    How can I get rid of the errors?

    - EDIT -

    I have added

    fileStream.Dispose();
    DeleteFile(tmpName);
    
    
    private static void DeleteFile(string filePath)
            {
                if (System.IO.File.Exists(filePath))
                {
                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch
                    {
                    }
                }
            }

    after reading the filestream. I also added the DeleteFile() to my catch.


    Still waiting for the test results.
    • Edited by WSPWesley Thursday, February 11, 2016 9:13 AM
    Tuesday, February 9, 2016 9:59 AM

Answers

  • >>>I tracked the error to mailItem.SaveAs(), but I still don't know the cause and how to solve it.

    According to your description, I suggest that you could save MailItem object as .msg file like below:

    String savepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + filename + ".msg";
    mailItem.SaveAs(savepath);

    In addition the Exception class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data. So I suggest that you could output exception detail information to track error.

    For more information, click here to refer about Exception Class


    • Edited by David_JunFeng Thursday, February 18, 2016 9:16 AM
    • Marked as answer by David_JunFeng Thursday, February 18, 2016 2:20 PM
    Friday, February 12, 2016 2:16 AM