Sdílet prostřednictvím


Creating Folders (WebDAV)

Topic Last Modified: 2006-06-12

To create a folder or collection using the World Wide Web Distributed Authoring and Versioning (WebDAV) protocol

  1. Create a WebDAV MKCOL Method request. The request Uniform Resource Identifier (URI) for the method is the URI to the collection that you are creating.

  2. Optionally, set properties for the new folder by sending an XML body in the request. You can set these properties in this request using the MKCOL Method or you can set these properties in a separate PROPPATCH Method after the folder is created. You format the XML the same way as when sending a PROPPATCH Method. For example:

    <d:propertyupdate xmlns:d="DAV:">
     <d:set>
       <d:prop>
        <d:displayname>Folder 1</d:displayname>
       </d:prop>
      </d:set>
    </d:propertyupdate>
    

    When sending a request body with the MKCOL Method, set the Content-Type header to "text/xml" and set the Content-Length header to the appropriate value.

  3. Send the request.

  4. If successful, the response status will be "201 Created".

See Constructing Exchange Store HTTP URLs and Authentication and Security Using WebDAV for more information.

This topic contains Microsoft® JScript®, Microsoft Visual C++®, Microsoft C#, and Microsoft Visual Basic® .NET code examples.

The following example shows a typical MKCOL Method request:

MKCOL /pub2/folder1/folder2/ HTTP/1.1
Host: hostname
Content-Type: text/xml
Content-Length: XXX

<?xml version="1.0"?>
<g:propertyupdate xmlns:g="DAV:" >
    <g:set>
        <g:prop>
            <g:displayname>value</g:displayname>
        </g:prop>
        <g:prop>
            <f:myprop xmlns:f="urn:schemas-mydomain-tld:">Test</f:myprop>
        </g:prop>
    </g:set>
</g:propertyupdate>

JScript

The following example uses an instance of the Microsoft.XMLHTTP Component Object Model (COM) class to send a MKCOL Method request to an Exchange store server.

Example

// Note: It is recommended that all input parameters be validated when they are
// first obtained from the user or user interface.
function createFolder( urisource, vXML ) {

 // Initialize the XMLHTTP request object.
 var Req = new ActiveXObject("Microsoft.XMLHTTP");

 // Open the request object with the MKCOL method and
 // specify that it will be sent asynchronously.
 Req.open("MKCOL", urisource, false);

 if(vXML != "")
 {
  // Set the Content-Type header to "text/xml".
  Req.setRequestHeader("Content-Type","text/xml");

  // Send the MKCOL method request with the specified
  // XML body.
  Req.send(vXML);
 }
 else
 {
  // Send the MKCOL method request.
  Req.send();
 }

 // An error occurred on the server.
 if(Req.status >= 500)
 {
   this.document.writeln("Status: " + Req.status);
   this.document.writeln("Status text: An error occurred on the server.");
 }

 else
 {
   this.document.writeln("Status: " + Req.status);
   this.document.writeln("Status text: " + Req.statustext);
 }

 return Req;

}

C++

The following example uses the MKCOL Method to create a collection in the Exchange store of type "IPF.Appointment".

Example

#include <stdio.h>
#include <iostream.h>

// If necessary, change the file path to match the location of the msxml.dll file.
#import "c:\windows\system32\msxml.dll"
using namespace MSXML;

// To use MSXML 4.0, import msxml4.dll instead of msxml.dll.
// #import "c:\windows\system32\msxml4.dll"
// using namespace MSXML2;

int main(int argc, char* argv[])
{
   CoInitialize(NULL);

   // Variables.
   MSXML::IXMLHttpRequest* pXMLHttpReq=NULL;
   bstr_t sUrl = "https://server/public/TestFolder";
   bstr_t sMethod = "MKCOL";
   _variant_t vUser = L"Domain\\Username";
   _variant_t vPassword = L"!Password";
   _variant_t vAsync = (bool)FALSE;
   bstr_t sReq ="";
   long lStatus = 0;
   BSTR bstrResp;
   BSTR bstrResponseText;
   HRESULT hr;

   // Initialize the XMLHTTPRequest object pointer.
   hr = ::CoCreateInstance(__uuidof(XMLHTTPRequest),
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           __uuidof(IXMLHttpRequest),
                          (LPVOID*)&pXMLHttpReq);

   // If you are using MSXML 4.0, use the following to initialize pXMLHttpReq:
   // IXMLHTTPRequestPtr pXMLHttpReq= NULL;
   // HRESULT hr=pXMLHttpReq.CreateInstance("Msxml2.XMLHTTP.4.0");

   // Check the status of pointer creation.
   if (S_OK != hr)
   {
      cout<< "XMLHttpRequest pointer creation failed." << endl;
      return 1;
   }

   try
   {
      // Open the XMLHTTPRequest object with the MKCOL method and
      // specify that it will be sent asynchronously.
      pXMLHttpReq->open(sMethod,
                        sUrl,
                        vAsync,
                        vUser,
                        vPassword);

      // Set the Content-Type header.
      pXMLHttpReq->setRequestHeader((bstr_t)"Content-Type",
                                    (bstr_t)"text/xml");

      // Create the XML request body and set the folder class to "IPF.Appointment".
      sReq =  "<?xml version='1.0'?>";
      sReq = sReq +
             "<a:propertyupdate xmlns:a=" +
             "'DAV:' xmlns:ex='https://schemas.microsoft.com/exchange/'>";
      sReq = sReq + "<a:set><a:prop>";
      sReq = sReq + "<ex:outlookfolderclass>" +
             "IPF.Appointment" + //TODO: Change to the desired folder class
             "</ex:outlookfolderclass>";
      sReq = sReq + "</a:prop></a:set></a:propertyupdate>";

      // Send the MKCOL method request.
      pXMLHttpReq->send(sReq);

      // Get the response status.
      pXMLHttpReq->get_status(&lStatus);

      // An error occurred on the server.
      if(lStatus >= 500)
      {
         cout << "Status: " << lStatus << endl
              << "Status text: An error occurred on the server."
              << endl;
      }

      else
      {
         // Display the response status.
         cout << "Status: " << lStatus << endl;

         // Display the response status text.
         pXMLHttpReq->get_statusText(&bstrResp);
         cout << "Status text: " << (char*)(bstr_t)bstrResp << endl;

         // Display the response text.
         pXMLHttpReq->get_responseText(&bstrResponseText);
         cout << "Response text: " << (char*)(bstr_t)bstrResponseText << endl;
      }

      // Release the memory.
      pXMLHttpReq->Release();

   }
   catch(_com_error &e)
   {
      // Display the error information.
      cout << "Error code: " << (char*)e.Error() << endl
           << "Error message: " << (char*)e.ErrorMessage()
           <<endl;

      // Release the memory.
      pXMLHttpReq->Release();

      return 1;
   }

   CoUninitialize();

   return 0;
}  

C#

The following example uses the System.Net.HttpWebRequest object to send a MKCOL Method request to an Exchange store server.

Example

using System;
using System.Net;

namespace ExchangeSDK.Snippets.CSharp
{
   class CreatingFoldersWebDAV
   {

      [STAThread]
      static void Main(string[] args)
      {
         // Variables.
         System.Net.HttpWebRequest Request;
         System.Net.WebResponse Response;
         System.Net.CredentialCache MyCredentialCache;
         string strFolderURI = "https://server/public/testfolder/";
         string strUserName = "UserName";
         string strPassword = "!Password";
         string strDomain = "Domain";

         try
         {
            // Create a new CredentialCache object and fill it with the network
            // credentials required to access the server.
            MyCredentialCache = new System.Net.CredentialCache();
            MyCredentialCache.Add( new System.Uri(strFolderURI),
               "NTLM",
               new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
               );

            // Create the HttpWebRequest object.
            Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strFolderURI);

            // Add the network credentials to the request.
            Request.Credentials = MyCredentialCache;

            // Specify the MKCOL method.
            Request.Method = "MKCOL";

            // Send the MKCOL method request, get the
            // method response from the server.
            Response = (System.Net.HttpWebResponse)Request.GetResponse();

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

            Console.WriteLine("Folder created at " + strFolderURI + ".");

         }
         catch(Exception ex)
         {
            // Catch any exceptions. Any error codes from the MKCOL
            // method request on the server will be caught here, also.
            Console.WriteLine(ex.Message);

         }
      }
   }
}

Visual Basic .NET

The following example uses the System.Net.HttpWebRequest object to send a MKCOL Method request to an Exchange store server.

Example

Option Explicit On
Option Strict On

Module Module1

Sub Main()

   ' Variables.
   Dim Request As System.Net.HttpWebRequest
   Dim Response As System.Net.HttpWebResponse
   Dim MyCredentialCache As System.Net.CredentialCache
   Dim strPassword As String
   Dim strDomain As String
   Dim strUserName As String
   Dim strFolderURI As String

   Try
      ' Initialize variables.
      strUserName = "UserName"
      strPassword = "!Password"
      strDomain = "Domain"
      strFolderURI = "https://server/public/testfolder/"

      ' Create a new CredentialCache object and fill it with the network
      ' credentials required to access the server.
      MyCredentialCache = New System.Net.CredentialCache
      MyCredentialCache.Add(New System.Uri(strFolderURI), _
          "NTLM", _
          New System.Net.NetworkCredential(strUserName, strPassword, strDomain) _
          )

      ' Create the HttpWebRequest object.
      Request = CType(System.Net.WebRequest.Create(strFolderURI), _
                      System.Net.HttpWebRequest)

      ' Add the network credentials to the request.
      Request.Credentials = MyCredentialCache

      ' Specify the method.
      Request.Method = "MKCOL"

      ' Send the MKCOL method request and get the
      ' response from the server.
      Response = CType(Request.GetResponse(), System.Net.HttpWebResponse)

      Console.WriteLine("Folder created at " + strFolderURI + ".")

      ' Clean up.
      Response.Close()

   Catch ex As Exception

      ' Catch any exceptions. Any error codes from the
      ' MKCOL method requests on the server will be caught
      ' here, also.
      Console.WriteLine(ex.Message)

   End Try

End Sub

End Module