Download Attachment using Webdav



  • Hi,

     I'm trying to download the attachment from exchange server using WebDav. I used below code. Yesterday it is working fine and successfully downloads all the attachments but when I try today to run it I get below error.

     The remote server returned an error: (400) Bad Request.

     Code:

     namespace ExchangeTest
    {
        public class WebDAV
        {
            public static class Authentications
            {
                public const string ANONYMOUS = "ANONYMOUS";
                public const string BASIC = "BASIC";
                public const string DIGEST = "DIGEST";
                public const string NTLM = "NTLM";
                public const string NEGOTIATE = "NEGOTIATE";
                public const string PASSPORT = "PASSPORT";
            }
            public static class Methods
            {
                public const string BCOPY = "BCOPY";
                public const string BDELETE = "BDELETE";
                public const string BMOVE = "BMOVE";
                public const string BPROPFIND = "BPROPFIND";
                public const string BPROPPATCH = "BPROPPATCH";
                public const string COPY = "COPY";
                public const string DELETE = "DELETE";
                public const string LOCK = "LOCK";
                public const string MKCOL = "MKCOL";
                public const string MOVE = "MOVE";
                public const string NOTIFY = "NOTIFY";
                public const string POLL = "POLL";
                public const string PROPFIND = "PROPFIND";
                public const string PROPPATCH = "PROPPATCH";
                public const string SEARCH = "SEARCH";
                public const string SUBSCRIBE = "SUBSCRIBE";
                public const string UNLOCK = "UNLOCK";
                public const string UNSUBSCRIBE = "UNSUBSCRIBE";
                public const string X_MS_ENUMATTS = "X-MS-ENUMATTS";
            }
            public const string CONTENT_TYPE_TEXT_XML = "text/xml";
            public const string NS_DAV = "DAV:";
            public const string PR_DAV_SEARCHREQUEST = "searchrequest";
            public const string PR_DAV_SQL = "sql";
            public const string PR_DAV_PROPFIND = "propfind";
            public const string PR_DAV_PROP = "prop";
            public const string PR_DAV_PROPERTYUPDATE = "propertyupdate";
            public const string PR_DAV_SET = "set";
            public const string PR_DAV_HREF = "href";
            public const string PR_DAV_PROPSTAT = "propstat";
            public const string PR_DAV_STATUS = "status";
            public const string PR_DAV_RESPONSE = "response";
            public const string NS_HTTPMAIL = "urn:schemas:httpmail:";
            public const string PR_HTTPMAIL_DATE = "date";
            public const string PR_HTTPMAIL_SUBJECT = "subject";
            public const string PR_HTTPMAIL_FROM = "from";
            public const string PR_HTTPMAIL_TO = "to";
            public const string PR_HTTPMAIL_READ = "read";
            public const string PR_HTTPMAIL_HASATTACHMENT = "hasattachment";
            public const string PR_HTTPMAIL_ATTACHMENTFILENAME = "attachmentfilename";
            public const string PR_HTTPMAIL_TEXTDESCRIPTION = "textdescription";
            public System.Net.ICredentials Credentials;
            public System.Xml.XmlDocument Search(System.Uri uri, string query)
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, null);
                writer.WriteStartDocument();
                writer.WriteStartElement(PR_DAV_SEARCHREQUEST, NS_DAV);
                writer.WriteStartElement(PR_DAV_SQL, NS_DAV);
                writer.WriteValue(query);
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                writer = null;
                byte[] data = ms.ToArray();
                ms.Close();
                ms = null;
                return GetXmlResponse(uri, Methods.SEARCH, data);
            }
            public System.Xml.XmlDocument PropFind(System.Uri uri, string localname, string ns)
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, null);
                writer.WriteStartDocument();
                writer.WriteStartElement(PR_DAV_PROPFIND, NS_DAV);
                writer.WriteStartElement(PR_DAV_PROP, NS_DAV);
                writer.WriteStartElement(localname, ns);
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                writer = null;
                byte[] data = ms.ToArray();
                ms.Close();
                ms = null;
                return GetXmlResponse(uri, Methods.SEARCH, data);
            }
            public void Delete(System.Uri uri)
            {
                GetEmptyResponse(uri, Methods.DELETE, null);
            }
            public System.Xml.XmlDocument PropPatch(System.Uri uri, string localname, string ns, object value)
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, null);
                writer.WriteStartDocument();
                writer.WriteStartElement(PR_DAV_PROPERTYUPDATE, NS_DAV);
                writer.WriteStartElement(PR_DAV_SET, NS_DAV);
                writer.WriteStartElement(PR_DAV_PROP, NS_DAV);
                writer.WriteStartElement(localname, ns);
                writer.WriteValue(value);
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                writer = null;
                byte[] data = ms.ToArray();
                ms.Close();
                ms = null;
                return GetXmlResponse(uri, Methods.PROPPATCH, data);
            }
            public System.Xml.XmlDocument EnumAtts(System.Uri uri)
            {
                return GetXmlResponse(uri, Methods.X_MS_ENUMATTS, null);
            }
            private string GetHtmlResponse(System.Uri uri, string method, byte[] data)
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
                request.Credentials = Credentials;
                request.Method = method;
                if (data != null)
                {
                    string xml = System.Text.Encoding.UTF8.GetString(data);
                    request.ContentType = CONTENT_TYPE_TEXT_XML;
                    request.ContentLength = data.Length;
                    System.IO.Stream requestStream = request.GetRequestStream();
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Close();
                }
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                int length = 8192;
                byte[] buffer = new byte[length];
                int count = responseStream.Read(buffer, 0, length);
                while (count > 0)
                {
                    memoryStream.Write(buffer, 0, count);
                    count = responseStream.Read(buffer, 0, length);
                }
                buffer = memoryStream.ToArray();
                memoryStream.Close();
                responseStream.Close();
                response.Close();
                return System.Text.Encoding.UTF8.GetString(buffer);
            }
            private void GetEmptyResponse(System.Uri uri, string method, byte[] data)
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
                request.Credentials = Credentials;
                request.Method = method;
                if (data != null)
                {
                    string xml = System.Text.Encoding.UTF8.GetString(data);
                    request.ContentType = CONTENT_TYPE_TEXT_XML;
                    request.ContentLength = data.Length;
                    System.IO.Stream requestStream = request.GetRequestStream();
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Close();
                }
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                response.Close();
            }
            private System.Xml.XmlDocument GetXmlResponse(System.Uri uri, string method, byte[] data)
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
                request.Credentials = Credentials;
                request.Method = method;
                if (data != null)
                {
                    string xml = System.Text.Encoding.UTF8.GetString(data);
                    request.ContentType = CONTENT_TYPE_TEXT_XML;
                    request.ContentLength = data.Length;
                    System.IO.Stream requestStream = request.GetRequestStream();
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Close();
                }
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream responseStream = response.GetResponseStream();
                System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                document.Load(responseStream);
                responseStream.Close();
                response.Close();
                return document;
            }
        }
        public class ExchangeDownloader
        {
            public string Username;
            public string Domain;
            public string Password;
            public string MailboxUrl;
            public string DownloadPath;
            public void Download()
            {
                System.Uri mailboxUri = new System.Uri(MailboxUrl);
                System.Net.NetworkCredential credential = new System.Net.NetworkCredential(Username, Password, Domain);
                WebDAV webdav = new WebDAV();
                System.Net.CredentialCache credentials = new System.Net.CredentialCache();
                credentials.Add(mailboxUri, WebDAV.Authentications.NTLM, credential);
                webdav.Credentials = credentials;
                System.Uri[] messageUris = getMessagesWithAttachments(webdav, mailboxUri);
                foreach (System.Uri messageUri in messageUris)
                {
                    System.Uri[] attachmentUris = getAttachments(webdav, messageUri);
                    foreach (System.Uri attachmentUri in attachmentUris)
                    {
                        downloadAttachment(webdav, attachmentUri);
                    }
                    webdav.PropPatch(messageUri, WebDAV.PR_HTTPMAIL_READ, WebDAV.NS_HTTPMAIL, "1");
                }
            }
            private void downloadAttachment(WebDAV webdav, System.Uri uri)
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.Credentials = webdav.Credentials;
                string file = System.IO.Path.GetFileName(uri.AbsolutePath);
                string filename = System.IO.Path.Combine(DownloadPath, file);
                webClient.DownloadFile(uri, filename);
            }
            private System.Uri[] getAttachments(WebDAV webdav, System.Uri uri)
            {
                System.Collections.ArrayList attachmentList = new System.Collections.ArrayList();
                System.Xml.XmlDocument document = webdav.EnumAtts(uri);
                System.Xml.XmlNodeList responseElements = document.GetElementsByTagName(WebDAV.PR_DAV_RESPONSE, WebDAV.NS_DAV);
                foreach (System.Xml.XmlElement responseElement in responseElements)
                {
                    System.Xml.XmlElement hrefElement = responseElement[WebDAV.PR_DAV_HREF, WebDAV.NS_DAV];
                    System.Uri href = new System.Uri(hrefElement.InnerText);
                    attachmentList.Add(href);
                }
                return (System.Uri[])attachmentList.ToArray(typeof(System.Uri));
            }
            private System.Uri[] getMessagesWithAttachments(WebDAV webdav, System.Uri uri)
            {
                System.Collections.ArrayList messageList = new System.Collections.ArrayList();
                string query = string.Format(
                    "SELECT \"urn:schemas:httpmail:subject\" " +
                    "FROM \"{0}\" " +
                    "WHERE \"urn:schemas:httpmail:hasattachment\"=true " +
                    "ORDER BY \"urn:schemas:httpmail:date DESC\""
                    , uri);
                System.Xml.XmlDocument document = webdav.Search(uri, query);
                System.Xml.XmlNodeList responseElements = document.GetElementsByTagName(WebDAV.PR_DAV_RESPONSE, WebDAV.NS_DAV);
                foreach (System.Xml.XmlElement responseElement in responseElements)
                {
                    System.Xml.XmlElement hrefElement = responseElement[WebDAV.PR_DAV_HREF, WebDAV.NS_DAV];
                    System.Uri href = new System.Uri(hrefElement.InnerText);
                    messageList.Add(href);
                }
                return (System.Uri[])messageList.ToArray(typeof(System.Uri));
            }
        }
        static class Program
        {
            static void Main()
            {
                ExchangeDownloader exchangeDownloader = new ExchangeDownloader();
                exchangeDownloader.Username = "username";
                exchangeDownloader.Domain = "domain";
                exchangeDownloader.Password = "password";
                exchangeDownloader.MailboxUrl = "http://server/exchange/account/inbox";
                exchangeDownloader.DownloadPath = "C:\\Downloads";
                exchangeDownloader.Download();
            }
        }
    }

     


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.