枫叶飞翔 发表于 2015-9-12 05:45:55

在C#中通过webdav操作exchange

  操作exchange类库代码




为日历中的约会定义的实体
using System;
using System.Collections;

namespace ISoftStone.AccessExchange.WebDav
{
    /**//// <summary>
    /// CalendarItemInfo 的摘要说明。
    /// </summary>
    public class CalendarItemInfo
    {
      private string mName;
      public string Name
      {
            get
            {
                return this.mName;
            }
            set
            {
                this.mName = value;
            }
      }
      private string mLocation;
      private DateTime mBeginTime ;
      private DateTime mEndTime;
      private int mInstanceType = 0;
      private string mBusyStatus = &quot;BUSY&quot;;
      private string mMeetingStatus = &quot;CONFIRMED&quot;;
      private bool mIsAllDayEvent = false;
      public bool IsAllDayEvent
      {
            get
            {
                return this.mIsAllDayEvent;
            }
            set
            {
                this.mIsAllDayEvent = value;
            }
      }
      private bool mResponseRequested = true;
      public bool ResponseRequested
      {
            get
            {
                return this.mResponseRequested;
            }
            set
            {
                this.mResponseRequested = value;
            }
      }
      privateint mReminderOffset = 900; //seconds
      public int ReminderOffset
      {
            get
            {
                return this.mReminderOffset;
            }
            set
            {
                this.mReminderOffset = value;
            }
      }
      private stringmMailToListMust;
      public string MailToListMust
      {
            get
            {
                return this.mMailToListMust;
            }
            set
            {
                this.mMailToListMust = value;
            }
      }
      private string mMailToList;
      public string MailToList
      {
            get
            {
                return this.mMailToList;
            }
            set
            {
                this.mMailToList = value;
            }
      }

      private string mSubject;
      public string Subject
      {
            get
            {
                return this.mSubject;
            }
            set
            {
                this.mSubject = value;
            }
      }
      private string mHtmlDescription;
      public string HtmlDescription
      {
            get
            {
                return this.mHtmlDescription;
            }
            set
            {
                this.mHtmlDescription = value;
            }
      }
      private bool mIsFinvited = true;
      public bool IsFinvited
      {
            get
            {
                return this.mIsFinvited;
            }
            set
            {
                this.mIsFinvited = value;
            }
      }
      /**//// <summary>
      /// 所在位置
      /// </summary>
      public string Location
      {
            get
            {
                return this.mLocation;
            }
            set
            {
                this.mLocation = value;
            }
      }
      /**//// <summary>
      /// 约会开始时间
      /// </summary>
      public DateTime BeginTime
      {
            get
            {
                return mBeginTime;
            }
            set
            {
                mBeginTime = value;
            }
      }
      /**//// <summary>
      /// 约会结束时间
      /// </summary>
      public DateTime EndTime
      {
            get
            {
                return this.mEndTime;
            }
            set
            {
                this.mEndTime = value;
            }
      }
      public int InstanceType
      {
            get
            {
                return this.mInstanceType;
            }
            set
            {
                this.mInstanceType = value;
            }
      }
      public string BusyStatus
      {
            get
            {
                return this.mBusyStatus;
            }
            set
            {
                this.mBusyStatus = value;
            }
      }
      public string MeetingStatus
      {
            get
            {
                return this.mMeetingStatus;

            }
            set
            {
                this.mMeetingStatus = value;
            }
      }

      public int GetBoolInt(bool any)
      {
            if (any)
            {
                return 1;
            }
            return 0;
      }
      

      public CalendarItemInfo()
      {
            //
            // TODO: 在此处添加构造函数逻辑
            //
      }
    }
}


User



using System;

namespace ISoftStone.AccessExchange.WebDav
{
    /**//// <summary>
    /// User 的摘要说明。
    /// </summary>
    public class User
    {
      private string m_Name;
      private string m_Password;
      private string m_Domain;

      public string Name
      {
            get
            {
                return m_Name;
            }
            set
            {
                m_Name = value;
            }
      }
      public string Password
      {
            get
            {
                return m_Password;
            }
            set
            {
                m_Password = value;
            }
      }

      public string Domain
      {
            get
            {
                return m_Domain;
            }
            set
            {
                m_Domain = value;
            }
      }
      private User(string name,string password,string domain)
      {
            m_Name = name;
            m_Password = password;
            m_Domain = domain;
      }
      public static User GetUser(string name,string password,string domain)
      {
            returnnew User(name,password,domain);
            
      }
      public static User GetUser(string name,string password)
      {
            return new User(name,password,String.Empty);
      }
    }
}

session

using System;
using System.Net;

namespace ISoftStone.AccessExchange.WebDav
{
    /**//// <summary>
    ///This class is for the session management of WebExchange class.
    /// </summary>
    public class WebDavSession
    {
      Fields#region Fields

      private string m_UserMailUrl;
      private ICredentials m_Credentials;
      private WebProxy m_Proxy;

      #endregion
      Property#region Property

      /**//// <summary>
      /// user's mailbox url
      /// </summary>
      public string UserMailUrl
      {
            get
            {
                return m_UserMailUrl;
            }
            set
            {
                m_UserMailUrl = value;
            }
      }
      /**//// <summary>
      /// web proxy
      /// </summary>
      public WebProxy Proxy
      {
            get
            {
                return m_Proxy;
            }
            set
            {
                m_Proxy = value;
            }
      }
      public ICredentials Credentials
      {
            get
            {
                return m_Credentials;
            }
            set
            {
                m_Credentials = value;
            }
      }
      #endregion

      public static WebDavSession GetSession(ICredentials obj)
      {
            WebDavSession session =new WebDavSession();
            session.Credentials = obj;
            return session;
      }
      public static WebDavSession GetSession(User user)
      {
            return GetSession(user,String.Empty);
      }
      public static WebDavSession GetSession(User user,WebProxy proxy)
      {
            return GetSession(user,String.Empty,proxy);
      }

      public static WebDavSession GetSession(User user,string userMailUrl)
      {
            return GetSession(user,userMailUrl,null);
      }
      public static WebDavSession GetSession(User user,string userMailUrl,WebProxy proxy)
      {
            WebDavSession session = new WebDavSession();
            session.UserMailUrl = userMailUrl;
            session.Proxy = proxy;
            if(user.Domain.Equals(String.Empty))
            {
                CredentialCache myCredentialCache = new CredentialCache();
                myCredentialCache.Add( new System.Uri(userMailUrl),&quot;NTLM&quot;,
                  new NetworkCredential(user.Name,user.Password));
                session.Credentials = myCredentialCache;
            }
            else
            {
                CredentialCache myCredentialCache = new CredentialCache();
                myCredentialCache.Add( new System.Uri(userMailUrl),&quot;NTLM&quot;,
                  new NetworkCredential(user.Name,user.Password,user.Domain));
                session.Credentials = myCredentialCache;
            }
            return session;
      }
      public WebDavSession()
      {
            //
            // TODO: 在此处添加构造函数逻辑
            //
      }
    }
}




using System;
using System.Net;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;

namespace ISoftStone.AccessExchange.WebDav
{
    /**//// <summary>
    /// WebExchange 的摘要说明。
    /// </summary>
    public class WebExchange
    {
      private WebDavSession m_Session;
      private string m_Url;
      private Encoding m_Encode;

      private HttpWebRequest objRequest;
      private WebResponse objResponse;

      
      

      public WebDavSession Session
      {
            get
            {
                if(m_Session == null)
                {
                  m_Session = new WebDavSession();
                }
                return m_Session;
            }
            set
            {
                m_Session = value;
            }
      }
      public string Url
      {
            get
            {
                if(m_Url != null)
                {
                  if(m_Url.LastIndexOf(&quot;/&quot;) == m_Url.Length -1)
                  {
                        return m_Url.Substring(0,m_Url.Length-1);
                  }
                }
                return m_Url;
            }
            set
            {
                m_Url = value;
            }
      }
      public Encoding Encode
      {
            get
            {
                if (m_Encode == null)
                {
                  m_Encode = new UTF8Encoding();
                }
                return m_Encode;
            }
            set
            {
                m_Encode = value;
            }
      }
      
      public WebExchange(WebDavSession webDavSession)
      {
            m_Session = webDavSession;
            m_Url = webDavSession.UserMailUrl;
      }
      public WebExchange(WebDavSession webDavSession,string url)
      {
            m_Session = webDavSession;
            m_Url = url;
      }
      public WebExchange(string url)
      {
            m_Url = url;
      }
      public void CreateCalendarItem(CalendarItemInfo itemInfo)
      {
            

            byte[] bytes = null;
            Stream requestStream = null;
            Stream responseStream = null;
            string strMailbox = &quot;jianli&quot;;
            string strXMLNSInfo =null;
            try
            {
                objRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(this.Url + &quot;/&quot; + itemInfo.Name);
                //objRequest = (HttpWebRequest)HttpWebRequest.Create(this.Url + &quot;/&quot; + &quot;testdee&quot;);
                // Add the network credentials to the request.
                objRequest.Credentials = Session.Credentials;
                // Specify the DELETE method.
                objRequest.Method = &quot;PROPPATCH&quot;;
                // XML namespace info for the WebDAV request.
                strXMLNSInfo = &quot;xmlns:g=\&quot;DAV:\&quot; &quot;
                  + &quot;xmlns:e=\&quot;http://schemas.microsoft.com/exchange/\&quot; &quot;
                  + &quot;xmlns:mapi=\&quot;http://schemas.microsoft.com/mapi/\&quot; &quot;
                  + &quot;xmlns:mapit=\&quot;http://schemas.microsoft.com/mapi/proptag/\&quot; &quot;
                  + &quot;xmlns:x=\&quot;xml:\&quot; xmlns:cal=\&quot;urn:schemas:calendar:\&quot; &quot;
                  + &quot;xmlns:dt=\&quot;urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\&quot; &quot;
                  + &quot;xmlns:header=\&quot;urn:schemas:mailheader:\&quot; &quot;
                  + &quot;xmlns:mail=\&quot;urn:schemas:httpmail:\&quot;&quot;;

                // Set the appointment item properties.To create an all-day meeting,
                // set the dtstart/dtend range for 24 hours or more and set the alldayevent property
                // to 1.See the documentation on the properties
                // in the urn:schemas:calendar: namespace for more information.
                string strCalInfo = &quot;<cal:location>&quot; + itemInfo.Location + &quot;</cal:location>&quot;
                  + &quot;<cal:dtstart dt:dt=\&quot;dateTime.tz\&quot;>2005-04-24T08:00:00.000Z</cal:dtstart>&quot;
               
                  + &quot;<cal:dtend dt:dt=\&quot;dateTime.tz\&quot;>2005-04-24T08:40:00.000Z</cal:dtend>&quot;
//                  + &quot;<cal:dtstart dt:dt=\&quot;dateTime.tz\&quot;>&quot; + itemInfo.BeginTime.ToShortDateString() + &quot;T&quot; + itemInfo.BeginTime.ToLongTimeString() + &quot;.000Z&quot; + &quot;</cal:dtstart>&quot;
//                  + &quot;<cal:dtend dt:dt=\&quot;dateTime.tz\&quot;>&quot;+ itemInfo.EndTime.ToShortDateString() + &quot;T&quot; + itemInfo.EndTime.ToLongTimeString() + &quot;.000Z&quot; +&quot;</cal:dtend>&quot;
                  + &quot;<cal:instancetype dt:dt=\&quot;int\&quot;>&quot; + itemInfo.InstanceType.ToString() + &quot;</cal:instancetype>&quot;
                  

                  

                  + &quot;<cal:busystatus>&quot; + itemInfo.BusyStatus + &quot;</cal:busystatus>&quot;
                  + &quot;<cal:meetingstatus> &quot; + itemInfo.MeetingStatus.ToString() + &quot;</cal:meetingstatus>&quot;
                  + &quot;<cal:alldayevent dt:dt=\&quot;boolean\&quot;>&quot; + itemInfo.GetBoolInt(itemInfo.IsAllDayEvent).ToString() + &quot;</cal:alldayevent>&quot;
                  + &quot;<cal:responserequested dt:dt=\&quot;boolean\&quot;>&quot; + itemInfo.GetBoolInt(itemInfo.IsAllDayEvent).ToString() + &quot;</cal:responserequested>&quot;
                  // Set the reminder time (in seconds).
                  + &quot;<cal:reminderoffset dt:dt=\&quot;int\&quot;>&quot; + itemInfo.ReminderOffset.ToString() +&quot;</cal:reminderoffset>&quot;;

//                string strCalInfo = &quot;<cal:location>meetappt Location</cal:location>&quot;
//                  + &quot;<cal:dtstart dt:dt=\&quot;dateTime.tz\&quot;>2004-05-18T23:00:00.000Z</cal:dtstart>&quot;
//                  + &quot;<cal:dtend dt:dt=\&quot;dateTime.tz\&quot;>2004-05-18T23:30:00.000Z</cal:dtend>&quot;
//                  + &quot;<cal:instancetype dt:dt=\&quot;int\&quot;>0</cal:instancetype>&quot;
//                  + &quot;<cal:busystatus>BUSY</cal:busystatus>&quot;
//                  + &quot;<cal:meetingstatus>CONFIRMED</cal:meetingstatus>&quot;
//                  + &quot;<cal:alldayevent dt:dt=\&quot;boolean\&quot;>0</cal:alldayevent>&quot;
//                  + &quot;<cal:responserequested dt:dt=\&quot;boolean\&quot;>1</cal:responserequested>&quot;
//
//                  // Set the reminder time (in seconds).
//                  + &quot;<cal:reminderoffset dt:dt=\&quot;int\&quot;>900</cal:reminderoffset>&quot;;
//
//


                // Set the required attendee of the appointment.
                string strHeaderInfo = &quot;<header:to>&quot; + itemInfo.MailToListMust + &quot;</header:to>&quot;;

                // Set the subject of the appointment.
                string strMailInfo = &quot;<mail:subject>&quot; + itemInfo.Subject + &quot;</mail:subject>&quot;
                  + &quot;<mail:htmldescription>&quot; + itemInfo.HtmlDescription + &quot;</mail:htmldescription>&quot;;

                // Build the XML body of the PROPPATCH request.
                string strApptRequest = &quot;<?xml version=\&quot;1.0\&quot;?>&quot;
                  + &quot;<g:propertyupdate &quot; + strXMLNSInfo + &quot;>&quot;
                  + &quot;<g:set><g:prop>&quot;
                  + &quot;<g:contentclass>urn:content-classes:appointment</g:contentclass>&quot;
                  + &quot;<e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>&quot;
                  + strMailInfo
                  + strCalInfo
                  + strHeaderInfo
                  + &quot;<mapi:finvited dt:dt=\&quot;boolean\&quot;>1</mapi:finvited>&quot;
                  + &quot;</g:prop></g:set>&quot;
                  + &quot;</g:propertyupdate>&quot;;


                bytes = this.Encode.GetBytes((string)strApptRequest);
               
                // Set the content header length.This must be
                // done before writing data to the request stream.
                objRequest.ContentLength = bytes.Length;

                // Get a reference to the request stream.
                requestStream = objRequest.GetRequestStream();

               
                // Write the request body to the request stream.
                requestStream.Write(bytes, 0, bytes.Length);

                // Close the Stream object to release the connection
                // for further use.
                requestStream.Close();

                // Set the content type header.
                objRequest.ContentType = &quot;text/xml&quot;;

                // Send the PROPFIND method request and get the
                // response from the server.
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                //return null;

                // Get the XML response stream.
                responseStream = objResponse.GetResponseStream();
                // Close the HttpWebResponse object.
                objResponse.Close();
                responseStream.Close();
                //Console.WriteLine(&quot;Item successfully deleted.&quot;)
            }
            catch(Exception ex)
            {
                // Catch any exceptions. Any error codes from the PROPPATCH
                // method request on the server will be caught
                // here, also.
                throw new Exception(&quot;can't create item &quot; + ex.ToString());
            }

      }
      public void CreateCalendarItem(string itemName)
      {
            byte[] bytes = null;
            Stream requestStream = null;
            Stream responseStream = null;
            string strMailbox = &quot;jianli&quot;;
            try
            {
                objRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(this.Url + &quot;/&quot; + itemName);

                // Add the network credentials to the request.
                objRequest.Credentials = this.Session.Credentials;

                // Specify the DELETE method.
                objRequest.Method = &quot;PROPPATCH&quot;;

                // XML namespace info for the WebDAV request.
                string strXMLNSInfo = &quot;xmlns:g=\&quot;DAV:\&quot; &quot;
                  + &quot;xmlns:e=\&quot;http://schemas.microsoft.com/exchange/\&quot; &quot;
                  + &quot;xmlns:mapi=\&quot;http://schemas.microsoft.com/mapi/\&quot; &quot;
                  + &quot;xmlns:mapit=\&quot;http://schemas.microsoft.com/mapi/proptag/\&quot; &quot;
                  + &quot;xmlns:x=\&quot;xml:\&quot; xmlns:cal=\&quot;urn:schemas:calendar:\&quot; &quot;
                  + &quot;xmlns:dt=\&quot;urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\&quot; &quot;
                  + &quot;xmlns:header=\&quot;urn:schemas:mailheader:\&quot; &quot;
                  + &quot;xmlns:mail=\&quot;urn:schemas:httpmail:\&quot;&quot;;

                // Set the appointment item properties.To create an all-day meeting,
                // set the dtstart/dtend range for 24 hours or more and set the alldayevent property
                // to 1.See the documentation on the properties
                // in the urn:schemas:calendar: namespace for more information.
                string strCalInfo = &quot;<cal:location>meetappt Location</cal:location>&quot;
                  + &quot;<cal:dtstart dt:dt=\&quot;dateTime.tz\&quot;>2004-05-18T23:00:00.000Z</cal:dtstart>&quot;
                  + &quot;<cal:dtend dt:dt=\&quot;dateTime.tz\&quot;>2004-05-18T23:30:00.000Z</cal:dtend>&quot;
                  + &quot;<cal:instancetype dt:dt=\&quot;int\&quot;>0</cal:instancetype>&quot;
                  + &quot;<cal:busystatus>BUSY</cal:busystatus>&quot;
                  + &quot;<cal:meetingstatus>CONFIRMED</cal:meetingstatus>&quot;
                  + &quot;<cal:alldayevent dt:dt=\&quot;boolean\&quot;>0</cal:alldayevent>&quot;
                  + &quot;<cal:responserequested dt:dt=\&quot;boolean\&quot;>1</cal:responserequested>&quot;

                  // Set the reminder time (in seconds).
                  + &quot;<cal:reminderoffset dt:dt=\&quot;int\&quot;>900</cal:reminderoffset>&quot;;

                // Set the required attendee of the appointment.
                string strHeaderInfo = &quot;<header:to>&quot; + strMailbox + &quot;;章清平 &lt;qpzhang@iisdnet.com &gt;></header:to>&quot;;

                // Set the subject of the appointment.
                string strMailInfo = &quot;<mail:subject>Test Appointment Subject</mail:subject>&quot;
                  + &quot;<mail:htmldescription>Let's meet here</mail:htmldescription>&quot;;

                // Build the XML body of the PROPPATCH request.
                string strApptRequest = &quot;<?xml version=\&quot;1.0\&quot;?>&quot;
                  + &quot;<g:propertyupdate &quot; + strXMLNSInfo + &quot;>&quot;
                  + &quot;<g:set><g:prop>&quot;
                  + &quot;<g:contentclass>urn:content-classes:appointment</g:contentclass>&quot;
                  + &quot;<e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>&quot;
                  + strMailInfo
                  + strCalInfo
                  + strHeaderInfo
                  + &quot;<mapi:finvited dt:dt=\&quot;boolean\&quot;>1</mapi:finvited>&quot;
                  + &quot;</g:prop></g:set>&quot;
                  + &quot;</g:propertyupdate>&quot;;


                bytes = this.Encode.GetBytes((string)strApptRequest);
               
                // Set the content header length.This must be
                // done before writing data to the request stream.
                objRequest.ContentLength = bytes.Length;

                // Get a reference to the request stream.
                requestStream = objRequest.GetRequestStream();

               
                // Write the request body to the request stream.
                requestStream.Write(bytes, 0, bytes.Length);

                // Close the Stream object to release the connection
                // for further use.
                requestStream.Close();

                // Set the content type header.
                objRequest.ContentType = &quot;text/xml&quot;;

               
                // Send the PROPFIND method request and get the
                // response from the server.
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                //return null;

                // Get the XML response stream.
                responseStream = objResponse.GetResponseStream();

                // Close the HttpWebResponse object.
                objResponse.Close();
                responseStream.Close();
               

                //Console.WriteLine(&quot;Item successfully deleted.&quot;)

            }
            catch(Exception ex)
            {
                // Catch any exceptions. Any error codes from the PROPPATCH
                // method request on the server will be caught
                // here, also.
                throw new Exception(&quot;can't create item &quot; + ex.ToString());
            }

      }
      public void GetInfo()
      {
//            string strXml;
//            strXml = &quot;<?xml version='&quot;+&quot;1.0&quot;+&quot;'?>&quot;;
//            strXml = strXml + &quot;<a:propfind xmlns:a='&quot;+&quot;DAV:&quot;+&quot;'xmlns:e='&quot;+&quot;urn:schemas:httpmail:'&quot;+&quot;>&quot;;
//            strXml = strXml + &quot;<a:prop>&quot;;
//            //日历
//            strXml = strXml + &quot;<e:calendar/>&quot;;
//            
//            //联系人
//            strXml = strXml + &quot;<e:contacts/>&quot;;
//            
//            //回收站
//            strXml = strXml + &quot;<e:deleteditems/>&quot;;
//            
//            //草稿
//            strXml = strXml + &quot;<e:drafts/>&quot;;
//            
//            //收件箱
//            strXml = strXml + &quot;<e:inbox/>&quot;;
//            
//            //日记
//            strXml = strXml + &quot;<e:journal/>&quot;;
//            
//            //便笺
//            strXml = strXml + &quot;<e:notes/>&quot;;
//            
//            //发件箱
//            strXml = strXml + &quot;<e:outbox/>&quot;;
//            
//            //已发邮件
//            strXml = strXml + &quot;<e:sentitems/>&quot;;
//            
//            //任务
//            strXml = strXml + &quot;<e:tasks/>&quot;;
//            
//            //短信
//            strXml = strXml + &quot;<e:sendmsg/>&quot;;
//            strXml = strXml + &quot;<e:msgfolderroot/>&quot;;
//            strXml = strXml + &quot;</a:prop>&quot;;
//            strXml = strXml + &quot;</a:propfind>&quot;;
//
//            //声明XMLHTTP对象
//            MSXML2.XMLHTTP30Class objXmlHttp=new MSXML2.XMLHTTP30Class();
//            //声明DOMDocument对象
//            MSXML2.DOMDocument30ClassobjXmlDOMDocument=new MSXML2.DOMDocument30Class();
//            objXmlHttp.open(&quot;PROPFIND&quot;,strUserFolder,false,strDomainName+&quot;\\&quot;+strUserName,strUserPwd);
//            objXmlHttp.setRequestHeader(&quot;content-type&quot;,&quot;text/xml&quot;);
//            objXmlHttp.setRequestHeader(&quot;depth&quot;,&quot;0&quot;);
//            objXmlHttp.send(strXml);
//   
//            if (objXmlHttp.status.ToString()==&quot;207&quot;) //DAV读取正确
//            {
//                objXmlDOMDocument.load(objXmlHttp.responseXML);
//               
//                //日历
//                strCalendar=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:calendar&quot;).text;
//               
//                //联系人
//                strContacts=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:contacts&quot;).text;
//               
//                //垃圾箱
//                strDeleteditems=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:deleteditems&quot;).text;
//               
//                //草稿
//                strDrafts=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:drafts&quot;).text;
//               
//                //收件箱
//                strInbox=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:inbox&quot;).text;
//               
//                //日记
//                strJournal=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:journal&quot;).text;
//               
//                //便笺
//                strNotes=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:notes&quot;).text;
//               
//                //发件箱
//                strOutbox=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:outbox&quot;).text;
//               
//                //已发邮件
//                strSentitems=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:sentitems&quot;).text;
//               
//                //任务
//                strTasks=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:tasks&quot;).text;
//                        
//                //短信
//                strSendmsg=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:sendmsg&quot;).text;
//               
//                strMsgfolderroot=objXmlDOMDocument.selectSingleNode(&quot;//a:multistatus/a:response/a:propstat/a:prop/d:msgfolderroot&quot;).text;
//               
//                //Label1.Text=strCalendar+strDeleteditems;//debug
//            }
//            else //DAV读取错误
//            {
//                Response.Write(&quot;<?xml version='1.0' encoding='GB2312'?>&quot;);
//                Response.Write(&quot;<Error>&quot;);
//                Response.Write(&quot;<Status>&quot; + objXmlHttp.status + &quot;</Status>&quot;);
//                Response.Write(&quot;<Statustext>&quot; + objXmlHttp.statusText.ToString() + &quot;</Statustext>&quot;);
//                Response.Write(&quot;</Error>&quot;);
//            }
//      



      }
      public XmlDocument SearchItems(string xmlSearchBody)
      {
            //string strSrcURI = ItemURL;

            byte[] bytes = null;
            Stream requestStream = null;
            Stream responseStream = null;
            XmlDocument responseXmlDoc = null;

            try
            {
               
                // Create the HttpWebRequest object.
                objRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
                // Add the network credentials to the request.
                objRequest.Credentials = m_Session.Credentials;
                // Specify the method.
                //objRequest.Method = &quot;PROPFIND&quot;;
                objRequest.Method = &quot;SEARCH&quot;;
                // Encode the body
                bytes = this.Encode.GetBytes((string)xmlSearchBody);
               
                // Set the content header length.This must be
                // done before writing data to the request stream.
                objRequest.ContentLength = bytes.Length;

                // Get a reference to the request stream.
                requestStream = objRequest.GetRequestStream();
               

                // Write the request body to the request stream.
                requestStream.Write(bytes, 0, bytes.Length);

                // Close the Stream object to release the connection
                // for further use.
                requestStream.Close();

                // Set the content type header.
                objRequest.ContentType = &quot;text/xml&quot;;

                // Send the PROPFIND method request and get the
                // response from the server.
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                //return null;

                // Get the XML response stream.
                responseStream = objResponse.GetResponseStream();

                // Create the XmlDocument object from the XML response stream.
                responseXmlDoc = new XmlDocument();
                responseXmlDoc.Load(responseStream);
               
                // Clean up.
                responseStream.Close();
                objResponse.Close();
               
                //responseXmlDoc.Save(@&quot;C:\jjj.xml&quot;);
                return responseXmlDoc;

            }
            catch(Exception e)
            {
                throw new Exception(&quot;Can't get the data&quot; + e.ToString());
            }   
      }
      public XmlDocument GetItemFieldValue(string strBody)
      {
            //string strSrcURI = ItemURL;

            byte[] bytes = null;
            Stream requestStream = null;
            Stream responseStream = null;
            XmlDocument responseXmlDoc = null;
            

            try
            {
               
                // Create the HttpWebRequest object.
                objRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
                // Add the network credentials to the request.
                objRequest.Credentials = m_Session.Credentials;
                // Specify the method.
                objRequest.Method = &quot;PROPFIND&quot;;
                //objRequest.Method = &quot;SEARCH&quot;;
                // Encode the body
                bytes = this.Encode.GetBytes((string)strBody);
               
                // Set the content header length.This must be
                // done before writing data to the request stream.
                objRequest.ContentLength = bytes.Length;

                // Get a reference to the request stream.
                requestStream = objRequest.GetRequestStream();
               

                // Write the request body to the request stream.
                requestStream.Write(bytes, 0, bytes.Length);

                // Close the Stream object to release the connection
                // for further use.
                requestStream.Close();

                // Set the content type header.
                objRequest.ContentType = &quot;text/xml&quot;;

                // Send the PROPFIND method request and get the
                // response from the server.
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                //return null;

                // Get the XML response stream.
                responseStream = objResponse.GetResponseStream();

                // Create the XmlDocument object from the XML response stream.
                responseXmlDoc = new XmlDocument();
                responseXmlDoc.Load(responseStream);
               
                // Clean up.
                responseStream.Close();
                objResponse.Close();
                responseXmlDoc.Save(@&quot;C:\jjj.xml&quot;);
                return responseXmlDoc;

            }
            catch(Exception e)
            {
                throw new Exception(&quot;Can't get the data&quot; + e.ToString());
            }            
      }
      /**//// <summary>
      /// 删除一个item
      /// </summary>
      /// <param name=&quot;itemUrl&quot;></param>
      public void DeleteItem(string itemUrl)
      {
            try
            {
                objRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(itemUrl);

                // Add the network credentials to the request.
                objRequest.Credentials = this.Session.Credentials;

                // Specify the DELETE method.
                objRequest.Method = &quot;DELETE&quot;;

                // Send the DELETE method request.
                objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

                // Close the HttpWebResponse object.
                objResponse.Close();

                //Console.WriteLine(&quot;Item successfully deleted.&quot;)

            }
            catch(Exception e)
            {
                throw new Exception(&quot;Can't delete the item&quot; + e.ToString());

            }
      }
      /**//// <summary>
      /// create a subfolder
      /// </summary>
      /// <param name=&quot;strBody&quot;></param>
      public void CreateFolder(string folderName)
      {
            //string strSrcURI = ItemURL;
            try
            {
                // Create the HttpWebRequest object.
                objRequest = (HttpWebRequest)HttpWebRequest.Create(Url + &quot;/&quot; + folderName);
                // Add the network credentials to the request.
                objRequest.Credentials = m_Session.Credentials;
                // Specify the method.
                objRequest.Method = &quot;MKCOL&quot;;

                objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

                // Close the HttpWebResponse object.
                objResponse.Close();
               
            }
            catch(Exception e)
            {
                throw new Exception(&quot;Can't create the foder&quot; + e.ToString());
            }            
      }
//      public DataSet GetDataFromXmlDocument(XmlDocument xml)
//      {
//            XmlDocument xd = new XmlDocument();
//            xd.LoadXml(&quot;<myroot>&quot; + FieldStr + &quot;</myroot>&quot;);
//            XPathNavigator xpn = xd.CreateNavigator();
//            XPathNodeIterator ni = xpn.Select(&quot;/myroot/Field&quot;);
//            while (ni.MoveNext())
//            {
//                SpsExpendFieldData objFieldData = SpsExpendFieldData.Create(ni.Current.GetAttribute(&quot;Name&quot;,&quot;&quot;),
//                  ni.Current.GetAttribute(&quot;ColName&quot;,&quot;&quot;),
//                  0,
//                  ni.Current.GetAttribute(&quot;Type&quot;,&quot;&quot;));
//                result.Add(objFieldData);
//            }
//            return result;
//      }
    }
}




WebExchange obj = new WebExchange(WebDavSession.GetSession(ISoftStone.AccessExchange.WebDav.User.GetUser(&quot;jianli&quot;,&quot;password&quot;,&quot;iisdnet&quot;),
                &quot;http://10.10.10.10/exchange/jianli/日历&quot;));

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(&quot; <?xml version=\&quot;1.0\&quot;?>&quot;);
            sb.Append(&quot; <D:searchrequest xmlns:D = \&quot;DAV:\&quot; >&quot;);
            sb.Append(&quot; <D:sql>&quot;);
            sb.Append(&quot; SELECT \&quot;DAV:displayname\&quot;&quot;);
            sb.Append(&quot; ,\&quot;DAV:href\&quot; &quot;);
            sb.Append(&quot;,\&quot;urn:schemas:calendar:dtstart\&quot; &quot;);
            sb.Append(&quot;,\&quot;urn:schemas:calendar:dtend\&quot; &quot;);
            sb.Append(&quot; ,\&quot;urn:schemas:calendar:location\&quot;&quot;);
            sb.Append(&quot;,\&quot;urn:schemas:calendar:busystatus\&quot; &quot;);
            sb.Append(&quot;,\&quot;urn:schemas:httpmail:subject\&quot;&quot;);
            sb.Append(&quot; ,\&quot;urn:schemas:httpmail:htmldescription\&quot;&quot; );
            sb.Append(&quot; FROM\&quot;http://10.10.10.10/exchange/jianli/日历\&quot;&quot;);
            sb.Append(&quot; WHERE \&quot;urn:schemas:calendar:dtstart\&quot; >= '&quot; + this.TBBeginTime.Text.Trim() + &quot;' &quot;);
            sb.Append(&quot; AND \&quot;urn:schemas:calendar:dtstart\&quot; &lt; '2006-01-01' &quot;);
            sb.Append(&quot; </D:sql></D:searchrequest> &quot;);



DataSet ds = new DataSet();
            DataTable db = new DataTable();
            ds.Tables.Add(db);
            
            ds.Tables.Columns.Add(&quot;displayname&quot;,System.Type.GetType(&quot;System.String&quot;));
            ds.Tables.Columns.Add(&quot;href&quot;,System.Type.GetType(&quot;System.String&quot;));
            ds.Tables.Columns.Add(&quot;dtstart&quot;,System.Type.GetType(&quot;System.DateTime&quot;));
            ds.Tables.Columns.Add(&quot;dtend&quot;,System.Type.GetType(&quot;System.DateTime&quot;));
            ds.Tables.Columns.Add(&quot;location&quot;,System.Type.GetType(&quot;System.String&quot;));
            ds.Tables.Columns.Add(&quot;busystatus&quot;,System.Type.GetType(&quot;System.String&quot;));
            ds.Tables.Columns.Add(&quot;subject&quot;,System.Type.GetType(&quot;System.String&quot;));
            ds.Tables.Columns.Add(&quot;htmldescription&quot;,System.Type.GetType(&quot;System.String&quot;));
            //ds.Tables.Columns.Add(&quot;href&quot;,System.Type.GetType(&quot;System.String&quot;));

            XmlDocument xd;
            //xd.Load(@&quot;C:\jjj.xml&quot;);
            xd = obj.SearchItems(sb.ToString());
      

            XPathNavigator xpn = xd.CreateNavigator();
            XPathExpression expr = xpn.Compile(&quot;//a:multistatus/a:response/a:propstat/a:prop&quot;);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xpn.NameTable);
            nsmgr.AddNamespace(&quot;a&quot;,&quot;DAV:&quot;);
            nsmgr.AddNamespace(&quot;d&quot;,&quot;urn:schemas:calendar:&quot;);
            expr.SetContext(nsmgr);

            XPathNodeIterator ni = xpn.Select(expr);
            Response.Write(ni.Count);
            while (ni.MoveNext())
            {
               
                //if(ni.Current.Value != &quot;&quot;)
                {
                  DataRow row = ds.Tables.NewRow();
                  XPathNodeIterator mi = ni.Current.SelectChildren(&quot;displayname&quot;,&quot;DAV:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;displayname&quot;] = mi.Current.Value;
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  mi = null;
                  mi = ni.Current.SelectChildren(&quot;href&quot;,&quot;DAV:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;href&quot;] = mi.Current.Value;
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  mi = null;
                  mi = ni.Current.SelectChildren(&quot;dtstart&quot;,&quot;urn:schemas:calendar:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;dtstart&quot;] = (Convert.ToDateTime(mi.Current.Value));
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  mi = null;
                  mi = ni.Current.SelectChildren(&quot;dtend&quot;,&quot;urn:schemas:calendar:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;dtend&quot;] = (Convert.ToDateTime(mi.Current.Value));//.AddHours(8);
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  mi = null;
                  mi = ni.Current.SelectChildren(&quot;location&quot;,&quot;urn:schemas:calendar:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;location&quot;] = mi.Current.Value;
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  mi = null;
                  mi = ni.Current.SelectChildren(&quot;busystatus&quot;,&quot;urn:schemas:calendar:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;busystatus&quot;] = mi.Current.Value;
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  mi = null;
                  mi = ni.Current.SelectChildren(&quot;subject&quot;,&quot;urn:schemas:httpmail:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;subject&quot;] = mi.Current.Value;
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  mi = null;
                  mi = ni.Current.SelectChildren(&quot;htmldescription&quot;,&quot;urn:schemas:httpmail:&quot;);
                  while(mi.MoveNext())
                  {
                        row[&quot;htmldescription&quot;] = mi.Current.Value;
                        //Response.Write(&quot;[&quot; + mi.Current.Value + &quot;]&quot;);
                  }
                  ds.Tables.Rows.Add(row);
                }

                //                SpsExpendFieldData objFieldData = SpsExpendFieldData.Create(ni.Current.GetAttribute(&quot;Name&quot;,&quot;&quot;),
                //                  ni.Current.GetAttribute(&quot;ColName&quot;,&quot;&quot;),
                //                  0,
                //                  ni.Current.GetAttribute(&quot;Type&quot;,&quot;&quot;));
                //                result.Add(objFieldData);
               
            }
exchange日历中的字段列表

最近工作中遇到些烦心的事,郁闷了好几天总也开心不起来,现在想通了

开心就好
页: [1]
查看完整版本: 在C#中通过webdav操作exchange