Search code examples
c#exchangewebservices

C# - The type initializer for 'Microsoft.Exchange.WebServices.Data.ExchangeServiceBase' threw an exception


I'm trying to get download attachments from emails out of a specific folder from an exchange server. But when I build the release I always get the error:

The type initializer for 'Microsoft.Exchange.WebServices.Data.ExchangeServiceBase' threw an exception. System.ArgumentException: The path is not of a legal form. at System.IO.Path.LegacyNormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)

My Code:

static void Main(string[] args)
    {            
        try
        {
            ExchangeService service = new ExchangeService();
            service.Credentials = new WebCredentials("email address", "password");
            //service.Url = new Uri("https://company/EWS/Exchange.asmx");
            service.AutodiscoverUrl("email address");

            List<SearchFilter> searchFilter = new List<SearchFilter>();
            searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Monitoring"));
            SearchFilter search = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilter.ToArray());

            Folder rootfolder = Folder.Bind(service, WellKnownFolderName.Inbox);
            foreach (Folder folder in rootfolder.FindFolders(new FolderView(100)))
            {
                if (folder.DisplayName.Contains("Monitoring"))
                {
                    ItemView view = new ItemView(100);
                    FindItemsResults<Item> findResults = service.FindItems(folder.Id, search, new ItemView(100));
                    Folder childfolder = Folder.Bind(service, folder.Id);

                    if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
                    {
                        foreach (Item item in findResults.Items)
                        {
                            EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
                            foreach (Attachment attachment in message.Attachments)
                            {
                                if (attachment is FileAttachment)
                                {
                                    FileAttachment fileAttachment = attachment as FileAttachment;
                                    string name = fileAttachment.Name.Substring(0, fileAttachment.Name.LastIndexOf('_')) + ".xml";
                                    string[] split = item.Subject.Split(';');
                                    string foldername = split[1];
                                    string path = Path.Combine(destination, foldername);
                                    string file = Path.Combine(path, fileAttachment.Name);

                                    if (!Directory.Exists(Path.Combine(destination, foldername)))
                                    {
                                        Directory.CreateDirectory(Path.Combine(destination, foldername));
                                    }

                                    fileAttachment.Load(file);
                                    Console.WriteLine(attachment.Name + " saved!");

                                    if (attachment.Name.Contains(".xml") || attachment.Name.Contains(".XML"))
                                    {
                                        decryptfile(Path.Combine(destination,foldername,attachment.Name),Path.Combine(destination,foldername,name));
                                        File.Delete(file);
                                        Console.WriteLine(attachment.Name + " decrypted to: " + name + ".xml");
                                    }                                            
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("no items");
                    }
                }
            }              
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc.Message);
            Console.WriteLine(exc.InnerException);
        }
    }

I'm wondering myself, why this is working fine on my test computer but in the productive environment, I get this error. Could this have something to do with outlook or missing rights?

Thank you.


Solution

  • Add the following setting in your application's configuration file, in the runtime section:

    <runtime>
            <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=true" /> 
    </runtime>
    

    for more information, visit https://msdn.microsoft.com/en-us/library/system.appcontext(v=vs.110).aspx