C# 通过指定公用文件夹的路径名搜索其文件夹

C# 通过指定公用文件夹的路径名搜索其文件夹,c#,web-services,api,exchange-server,managed,C#,Web Services,Api,Exchange Server,Managed,是否可以通过使用Exchange Web Service(EWS)托管Api提供文件夹的路径来搜索公用文件夹中的所有文件夹和文件夹?您只能在文件夹内搜索,在EWS上搜索一级,以便: PublicFoldersRoot\subjectA\sectionB\partC\ 我会搜索“subjectA”文件夹,一旦我有了这个文件夹ID,我就会搜索“sectionB”文件夹等等,直到我找到我需要的东西 方法GetPublicFolderByPath获取路径“subjectA\sectonB\partC\”

是否可以通过使用Exchange Web Service(EWS)托管Api提供文件夹的路径来搜索公用文件夹中的所有文件夹和文件夹?

您只能在文件夹内搜索,在EWS上搜索一级,以便:

PublicFoldersRoot\subjectA\sectionB\partC\

我会搜索“subjectA”文件夹,一旦我有了这个文件夹ID,我就会搜索“sectionB”文件夹等等,直到我找到我需要的东西

方法
GetPublicFolderByPath
获取路径“subjectA\sectonB\partC\”并将路径拆分为文件夹名称数组,然后递归查找每个文件夹

public Folder GetPublicFolderByPath(ExchangeService service, String ewsFolderPath)
{
    String[] folders = ewsFolderPath.Split('\');

    Folder parentFolderId = null;
    Folder actualFolder = null;

    for (int i = 0; i < folders.Count(); i++)
    {
        if (0 == i)
        {
            parentFolderId = GetTopLevelFolder(service, folders[i]);// for first first loop public folder root is the parent
            actualFolder = parentFolderId; //in case folders[] is only one long
        }
        else
        {
            actualFolder = GetFolder(service, parentFolderId.Id, folders[i]);
            parentFolderId = actualFolder;
        }
    }
    return actualFolder;
}
GetFolder
方法获取父文件夹ID,并在所有子文件夹中搜索名称上的匹配项,然后返回您请求的子文件夹ID

private Folder GetFolder(ExchangeService service, FolderId ParentFolderId, String folderName)
    {
        FolderView folderView = new FolderView(int.MaxValue);
        FindFoldersResults findFolderResults = service.FindFolders(ParentFolderId, folderView);

        foreach (Folder folder in findFolderResults)
        {
            if (folderName.Equals(folder.DisplayName, StringComparison.InvariantCultureIgnoreCase))
            {
                return folder;
            }
        }

        throw new Exception("Folder not found: " + folderName);

    }
请注意,我使用的是Microsoft.Exchange.WebServices托管API dll,与
https://yourexchangeserver/ews/services.wsdl
。要从路径中获取文件夹,请创建ExchangeService对象,然后写入:
GetPublicFolderByPath(服务,“subjectA\sectionB\partC\”)


如果这对你有帮助,请投票:)

这是一个基于@ono2012答案的包装

using System;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Exchange.WebServices.Data;

namespace EmailServices.Web.IntegrationTests
{
    // http://msdn.microsoft.com/en-us/library/exchange/jj220499(v=exchg.80).aspx
    internal class MsExchangeServices
    {
        public MsExchangeServices()
        {
            ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
            m_exchangeService = new ExchangeService { UseDefaultCredentials = true };

            // Who's running this test? They better have Exchange mailbox access.
            m_exchangeService.AutodiscoverUrl(UserPrincipal.Current.EmailAddress, RedirectionUrlValidationCallback);
        }

        public ExchangeService Service { get { return m_exchangeService; } }

        public Folder GetPublicFolderByPath(string ewsFolderPath)
        {
            string[] folders = ewsFolderPath.Split('\\');

            Folder parentFolderId = null;
            Folder actualFolder = null;

            for (int i = 0; i < folders.Length; i++)
            {
                if (0 == i)
                {
                    parentFolderId = GetTopLevelFolder(folders[i]);
                    actualFolder = parentFolderId;
                }
                else
                {
                    actualFolder = GetFolder(parentFolderId.Id, folders[i]);
                    parentFolderId = actualFolder;
                }
            }
            return actualFolder;
        }

        private static bool RedirectionUrlValidationCallback(string redirectionUrl)
        {
            // The default for the validation callback is to reject the URL.
            bool result = false;

            Uri redirectionUri = new Uri(redirectionUrl);

            // Validate the contents of the redirection URL. In this simple validation
            // callback, the redirection URL is considered valid if it is using HTTPS
            // to encrypt the authentication credentials. 
            if (redirectionUri.Scheme == "https")
                result = true;

            return result;
        }

        private static bool CertificateValidationCallBack(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == 0)
            {
                // In all other cases, return false.
                return false;
            }
            else
            {
                if (chain != null)
                {
                    foreach (X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) && (status.Status == X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                        }
                        else
                        {
                            if (status.Status != X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return false;
                            }
                        }
                    }
                }

                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }
        }

        private Folder GetTopLevelFolder(string folderName)
        {
            FindFoldersResults findFolderResults = m_exchangeService.FindFolders(WellKnownFolderName.PublicFoldersRoot, new FolderView(int.MaxValue));
            foreach (Folder folder in findFolderResults.Where(folder => folderName.Equals(folder.DisplayName, StringComparison.InvariantCultureIgnoreCase)))
                return folder;

            throw new Exception("Top Level Folder not found: " + folderName);
        }

        private Folder GetFolder(FolderId parentFolderId, string folderName)
        {
            FindFoldersResults findFolderResults = m_exchangeService.FindFolders(parentFolderId, new FolderView(int.MaxValue));
            foreach (Folder folder in findFolderResults.Where(folder => folderName.Equals(folder.DisplayName, StringComparison.InvariantCultureIgnoreCase)))
                return folder;

            throw new Exception("Folder not found: " + folderName);
        }

        readonly ExchangeService m_exchangeService;
    }
}
使用系统;
使用System.DirectoryServices.AccountManagement;
使用System.Linq;
Net系统;
使用System.Net.Security;
使用System.Security.Cryptography.X509证书;
使用Microsoft.Exchange.WebServices.Data;
命名空间EmailServices.Web.IntegrationTests
{
// http://msdn.microsoft.com/en-us/library/exchange/jj220499(v=exchg.80).aspx
内部类MsExchangeServices
{
公共MsExchangeServices()
{
ServicePointManager.ServerCertificateValidationCallback=CertificateValidationCallBack;
m_exchangeService=new exchangeService{UseDefaultCredentials=true};
//谁在运行此测试?他们最好具有Exchange邮箱访问权限。
m_exchangeService.AutoDiscoveryURL(UserPrincipal.Current.EmailAddress,RedirectionUrlValidationCallback);
}
公共ExchangeService服务{get{return m_ExchangeService;}}
公用文件夹GetPublicFolderByPath(字符串ewsFolderPath)
{
string[]folders=ewsFolderPath.Split('\\');
文件夹parentFolderId=null;
文件夹实际文件夹=null;
对于(int i=0;ifolderName.Equals(Folder.DisplayName,StringComparison.InvariantCultureIgnoreCase))中的文件夹)
返回文件夹;
抛出新异常(“未找到顶级文件夹:“+folderName”);
}
私有文件夹GetFolder(文件夹ID parentFolderId,字符串
using System;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Exchange.WebServices.Data;

namespace EmailServices.Web.IntegrationTests
{
    // http://msdn.microsoft.com/en-us/library/exchange/jj220499(v=exchg.80).aspx
    internal class MsExchangeServices
    {
        public MsExchangeServices()
        {
            ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
            m_exchangeService = new ExchangeService { UseDefaultCredentials = true };

            // Who's running this test? They better have Exchange mailbox access.
            m_exchangeService.AutodiscoverUrl(UserPrincipal.Current.EmailAddress, RedirectionUrlValidationCallback);
        }

        public ExchangeService Service { get { return m_exchangeService; } }

        public Folder GetPublicFolderByPath(string ewsFolderPath)
        {
            string[] folders = ewsFolderPath.Split('\\');

            Folder parentFolderId = null;
            Folder actualFolder = null;

            for (int i = 0; i < folders.Length; i++)
            {
                if (0 == i)
                {
                    parentFolderId = GetTopLevelFolder(folders[i]);
                    actualFolder = parentFolderId;
                }
                else
                {
                    actualFolder = GetFolder(parentFolderId.Id, folders[i]);
                    parentFolderId = actualFolder;
                }
            }
            return actualFolder;
        }

        private static bool RedirectionUrlValidationCallback(string redirectionUrl)
        {
            // The default for the validation callback is to reject the URL.
            bool result = false;

            Uri redirectionUri = new Uri(redirectionUrl);

            // Validate the contents of the redirection URL. In this simple validation
            // callback, the redirection URL is considered valid if it is using HTTPS
            // to encrypt the authentication credentials. 
            if (redirectionUri.Scheme == "https")
                result = true;

            return result;
        }

        private static bool CertificateValidationCallBack(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == 0)
            {
                // In all other cases, return false.
                return false;
            }
            else
            {
                if (chain != null)
                {
                    foreach (X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) && (status.Status == X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                        }
                        else
                        {
                            if (status.Status != X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return false;
                            }
                        }
                    }
                }

                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }
        }

        private Folder GetTopLevelFolder(string folderName)
        {
            FindFoldersResults findFolderResults = m_exchangeService.FindFolders(WellKnownFolderName.PublicFoldersRoot, new FolderView(int.MaxValue));
            foreach (Folder folder in findFolderResults.Where(folder => folderName.Equals(folder.DisplayName, StringComparison.InvariantCultureIgnoreCase)))
                return folder;

            throw new Exception("Top Level Folder not found: " + folderName);
        }

        private Folder GetFolder(FolderId parentFolderId, string folderName)
        {
            FindFoldersResults findFolderResults = m_exchangeService.FindFolders(parentFolderId, new FolderView(int.MaxValue));
            foreach (Folder folder in findFolderResults.Where(folder => folderName.Equals(folder.DisplayName, StringComparison.InvariantCultureIgnoreCase)))
                return folder;

            throw new Exception("Folder not found: " + folderName);
        }

        readonly ExchangeService m_exchangeService;
    }
}