How to download a file version from office 365 using csom

I need to download an older file version from office 365 and get the data into a byte array. I have no trouble downloading the latest version with File.OpenBinaryStream() and I have no trouble loading the previous file versions with File.Versions. But now
I need to actually download an older version of the file and it seems the only way is to use File.OpenBinaryDirect. So I am creating a client context using my oAuth access token and providing the correct path, but I am getting a (401) Unauthorized
error. Looking with Fiddler I can see that the call to OpenBinaryDirect is somehow trying to post to my file URL and the server is responding with 401.
context = TokenHelper.GetClientContextWithAccessToken(SPHostUrl, AccessToken);
FileInformation info = File.OpenBinaryDirect(context, "/" + _fileVersion.Url);  //throws 401
//leading slash required otherwise ArgumentOutOfRangeException
I have to be able to access the older file versions with my c# code -- I don't have a viable app without that ability -- any help urgently needed and greatly appreciated!

Thank you SO much (Can't wait for the next release)!
For anyone else who lands here, here's the code I ended up using:
// VersionAccessUser and VersionAccessPassword are stored in web.config
// web.Url is loaded via the clientContext
// myVersion is the FileVersion I got from the file's Versions.GetById() method
// probably a lot of ways to get hostUrl, it just needs to be
// - I'm running my app from a subweb
// I had trouble following the links to get the full MsOnlineClaimsHelper code
// (the one on was missing RequestBodyWriter, WSTrustFeb2005ContractClient,
// and IWSTrustFeb2005Contract
// so I've included the code I used here.
string myVersionFullUrl = string.Format("{0}/{1}", web.Url, myVersion.Url);
string userName = WebConfigurationManager.AppSettings.Get("VersionAccessUser");
string strPassword = WebConfigurationManager.AppSettings.Get("VersionAccessPassword");
string hostUrl = Regex.Replace(web.Url, "([^/]+//[^/]+/).*", "$1");
MsOnlineClaimsHelper claimsHelper = new MsOnlineClaimsHelper(hostUrl, userName, strPassword);
var client = new WebClient();
client.Headers["Accept"] = "/";
client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Headers.Add(HttpRequestHeader.Cookie, claimsHelper.CookieContainer.GetCookieHeader(new Uri(hostUrl)));
var document = client.DownloadString(myVersionFullUrl);
// These classes are needed to download old versions of files (see:
// I cobbled this file from
// and
using Microsoft.IdentityModel.Protocols.WSTrust;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Linq;
namespace DPSiDoxAppWeb.Helpers
/// <summary>
/// Create a new contract to use for issue claims for the SharePoint requests
/// </summary>
public interface IWSTrustFeb2005Contract
[OperationContract(ProtectionLevel = ProtectionLevel.EncryptAndSign,
Action = "",
ReplyAction = "",
AsyncPattern = true)]
IAsyncResult BeginIssue(Message request, AsyncCallback callback, object state);
Message EndIssue(IAsyncResult asyncResult);
/// <summary>
/// Implement the client contract for the new type
/// </summary>
public class WSTrustFeb2005ContractClient : ClientBase<IWSTrustFeb2005Contract>, IWSTrustFeb2005Contract
public WSTrustFeb2005ContractClient(Binding binding, EndpointAddress remoteAddress)
: base(binding, remoteAddress)
public IAsyncResult BeginIssue(Message request, AsyncCallback callback, object state)
return Channel.BeginIssue(request, callback, state);
public Message EndIssue(IAsyncResult asyncResult)
return Channel.EndIssue(asyncResult);
/// <summary>
/// Create a class that will serialize the token into the request
/// </summary>
class RequestBodyWriter : BodyWriter
readonly WSTrustRequestSerializer _serializer;
readonly RequestSecurityToken _rst;
/// <summary>
/// Constructs the Body Writer.
/// </summary>
/// <param name="serializer">Serializer to use for serializing the rst.</param>
/// <param name="rst">The RequestSecurityToken object to be serialized to the outgoing Message.</param>
public RequestBodyWriter(WSTrustRequestSerializer serializer, RequestSecurityToken rst)
: base(false)
if (serializer == null)
throw new ArgumentNullException("serializer");
_serializer = serializer;
_rst = rst;
/// <summary>
/// Override of the base class method. Serializes the rst to the outgoing stream.
/// </summary>
/// <param name="writer">Writer to which the rst should be written.</param>
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
_serializer.WriteXml(_rst, writer, new WSTrustSerializationContext());
public class MsOnlineClaimsHelper
#region Properties
readonly string _username;
readonly string _password;
readonly bool _useRtfa;
readonly Uri _host;
CookieContainer _cachedCookieContainer = null;
DateTime _expires = DateTime.MinValue;
#region Constructors
public MsOnlineClaimsHelper(string host, string username, string password)
: this(new Uri(host), username, password)
public MsOnlineClaimsHelper(Uri host, string username, string password)
_host = host;
_username = username;
_password = password;
_useRtfa = true;
public MsOnlineClaimsHelper(Uri host, string username, string password, bool useRtfa)
_host = host;
_username = username;
_password = password;
_useRtfa = useRtfa;
#region Constants
public const string office365STS = "";
public const string office365Login = "";
public const string office365Metadata = "";
public const string wsse = "";
public const string wsu = "";
private const string userAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
class MsoCookies
public string FedAuth { get; set; }
public string rtFa { get; set; }
public DateTime Expires { get; set; }
public Uri Host { get; set; }
// Method used to add cookies to CSOM
public void clientContext_ExecutingWebRequest(object sender, WebRequestEventArgs e)
e.WebRequestExecutor.WebRequest.CookieContainer = getCookieContainer();
//e.WebRequestExecutor.WebRequest.UserAgent = userAgent;
// Creates or loads cached cookie container
CookieContainer getCookieContainer()
if (_cachedCookieContainer == null || DateTime.Now > _expires)
// Get the SAML tokens from SPO STS (via MSO STS) using fed auth passive approach
MsoCookies cookies = getSamlToken();
if (cookies != null && !string.IsNullOrEmpty(cookies.FedAuth))
// Create cookie collection with the SAML token
_expires = cookies.Expires;
CookieContainer cc = new CookieContainer();
// Set the FedAuth cookie
Cookie samlAuth = new Cookie("FedAuth", cookies.FedAuth)
Expires = cookies.Expires,
Path = "/",
Secure = cookies.Host.Scheme == "https",
HttpOnly = true,
Domain = cookies.Host.Host
if (_useRtfa)
// Set the rtFA (sign-out) cookie, added march 2011
Cookie rtFa = new Cookie("rtFA", cookies.rtFa)
Expires = cookies.Expires,
Path = "/",
Secure = cookies.Host.Scheme == "https",
HttpOnly = true,
Domain = cookies.Host.Host
_cachedCookieContainer = cc;
return cc;
return null;
return _cachedCookieContainer;
public CookieContainer CookieContainer
if (_cachedCookieContainer == null || DateTime.Now > _expires)
return getCookieContainer();
return _cachedCookieContainer;
private MsoCookies getSamlToken()
MsoCookies ret = new MsoCookies();
var sharepointSite = new
Wctx = office365Login,
Wreply = _host.GetLeftPart(UriPartial.Authority) + "/_forms/default.aspx?wa=wsignin1.0"
//get token from STS
string stsResponse = getResponse(office365STS, sharepointSite.Wreply);
// parse the token response
XDocument doc = XDocument.Parse(stsResponse);
// get the security token
var crypt = from result in doc.Descendants()
where result.Name == XName.Get("BinarySecurityToken", wsse)
select result;
// get the token expiration
var expires = from result in doc.Descendants()
where result.Name == XName.Get("Expires", wsu)
select result;
ret.Expires = Convert.ToDateTime(expires.First().Value);
HttpWebRequest request = createRequest(sharepointSite.Wreply);
byte[] data = Encoding.UTF8.GetBytes(crypt.FirstOrDefault().Value);
using (Stream stream = request.GetRequestStream())
stream.Write(data, 0, data.Length);
using (HttpWebResponse webResponse = request.GetResponse() as HttpWebResponse)
// Handle redirect, added may 2011 for P-subscriptions
if (webResponse.StatusCode == HttpStatusCode.MovedPermanently)
HttpWebRequest request2 = createRequest(webResponse.Headers["Location"]);
using (Stream stream2 = request2.GetRequestStream())
stream2.Write(data, 0, data.Length);
using (HttpWebResponse webResponse2 = request2.GetResponse() as HttpWebResponse)
ret.FedAuth = webResponse2.Cookies["FedAuth"].Value;
ret.rtFa = webResponse2.Cookies["rtFa"].Value;
ret.Host = request2.RequestUri;
ret.FedAuth = webResponse.Cookies["FedAuth"].Value;
ret.rtFa = webResponse.Cookies["rtFa"].Value;
ret.Host = request.RequestUri;
catch (Exception ex)
return null;
return ret;
static HttpWebRequest createRequest(string url)
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = false; // Do NOT automatically redirect
request.UserAgent = userAgent;
return request;
private string getResponse(string stsUrl, string realm)
RequestSecurityToken rst = new RequestSecurityToken
RequestType = WSTrustFeb2005Constants.RequestTypes.Issue,
AppliesTo = new EndpointAddress(realm),
KeyType = WSTrustFeb2005Constants.KeyTypes.Bearer,
TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml11TokenProfile11
WSTrustFeb2005RequestSerializer trustSerializer = new WSTrustFeb2005RequestSerializer();
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.Security.Message.EstablishSecurityContext = false;
binding.Security.Message.NegotiateServiceCredential = false;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
EndpointAddress address = new EndpointAddress(stsUrl);
using (WSTrustFeb2005ContractClient trustClient = new WSTrustFeb2005ContractClient(binding, address))
trustClient.ClientCredentials.UserName.UserName = _username;
trustClient.ClientCredentials.UserName.Password = _password;
Message response = trustClient.EndIssue(
new RequestBodyWriter(trustSerializer, rst)
using (XmlDictionaryReader reader = response.GetReaderAtBodyContents())
return reader.ReadOuterXml();

Similar Messages

  • Disable site sharing in Office 365 using CSOM

    I have a requirement to disable sharing of sites and documents in Office 365 site collection using CSOM.
    Manually from UI, I can disable sharing by unchecking Access Request Settings under Site Settings.
    But could not find a way to do it using CSOM.

    If it is an on premises environment, there is a property “RequestAccessEnabled” in SPWeb class in SharePoint Object Model can be used to change the
    However, in an online environment, the SharePoint Object Model is not an option, what’s more, in Client Object Model which is designed for client side use, there is
    no such a property in Web class available:
    It means that it is not able to change the “Access Request Settings” with the client side technology such as JavaScript.
    Thus, I would suggest you submit a feedback to the Office Developer Platform if there any expectation about the future version of Office 365:
    is a place for customers provide feedback about Microsoft Office products. What’s more, if a feedback is high voted there by other customers, it will be promising that Microsoft
    Product Team will take it into consideration when designing the next version in the future.
    Best regards
    Patrick Liang
    TechNet Community Support

  • Is it possible to download a mail(.eml) from outlook 365 using exchange service and store in database using c#

    Hi All,
    I have a outlook mail account ex:- my mail account id is
    [email protected] , using c# code and Microsoft.Exchange.WebServices ,
     I want to download entair email and want to save this email in database , is it possible suggest me how can I go forward on this, if not possible please suggest some alternative ways to find the solution.
    the reason want to store this entair mail is  on click on some button I want to open this mail from database in .eml format with attachments if any are there.
    Thank in Advance

    Hello Ravi,
    Try this:
    With regards,
    Michael | Microsoft Exchange Developer Content
    Exchange Development Forum Guide has useful information for using the Exchange Development Forum.
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • How to Download a file from remote system.

    If anybody knows how to download a file directly from database to localdirectory

    I have data in a blob column of one table.
    from a html page if i click download link then a download dialog box shoud come saying save and cancle etc ., the blobdata from database should be retrived and stored in desired loaction in client system.

  • How to find .pld files version in Oracle apps

    How to find .pld file version in Oracle apps using unix command or any other way.

    Connect to the forms server.
    In the $AU_TOP/resource directory run the following...
    strings -a <NAMEOFFILE>.plx | grep '$Header'
    For example...
    To find the .pld version of INVAMCAP.plx I would run this on the forms server.
    cd $AU_TOP/resource
    strings -a INVAMCAP.plx | grep '$Header'
    This will return the .pld version.
    Hope this helps!

  • How can I download content of wiki pages from Office 365 online Sharepoint site using c#?

    How can I download content of wiki pages from Office 365 online Sharepoint site using c#?

    According to your post, my understanding is that you want to download content of wiki pages on SharePoint Online.
    If just for getting the text of the page, I suggest you convert page to PDF file first and then download the PDF file via a Visual Web Part as a Sandboxed solution.
    A sample about export HTML to PDF:
    Patrick Liang
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Patrick Liang
    TechNet Community Support

  • How to download a file from database

    My flex application contains a form that uploads a file into the server. This file is however saved in the database, and not on the disk. Most of the tutorials in the database explains how to download a file by passing the file's url to the "download" function of the fileReference Object. That dsnt work for me as my file is saved in the database.
    How do I download this file from the server ?
    For example, in php, we would do smthing like this :
    $content = $file_to_download['content'];
    $size = $file_to_download['content_size'];
    $type = $file_to_download['content_type'];
    $name = $file_to_download['filename'];
    header("Content-Description:PHP Generated Data");
    echo $content;
    When executing this file, it opens up the "download file" dialog box. How do i get the same effect in flex 4 ?

    You need the bytes use and after download you can save
    it on disk with; You also need FP 10 at least I think. Use
    the docs they are less error pron than mi memory :).

  • How to download a file from the net and save it into .txt format in a datab

    Can some one show me a tutorial on how to download a file from the net and save it into .txt format in a database?
    Thank you,

  • How to download a file from Path specifed

    Hi Frndz..
    How to download a file from a specified path like  , i have a file on server in the path like "C://temp/Sap.pdf"
    I want to download this to user desktop..
    Thanks in Advance

    For file down load u have to use a UI element as "File download".
    u just create context attribute as setdownload_res and file data.
    setdownload_res as of type "" then bound it to the ui element "resource".
    file data as of type ""
    and set calcuclated as true and read only as true.
    then in doinit method u just write this code
    IWDAttributePointer attr = wdContext.currentContextElement().getAttributePointer("fileData");
    IWDResource res = WDResourceFactory.createResource(attr,null,WDWebResourceType.UNKNOWN);
    after this in the getter method u write this code
    IWDInputStream stream = null;
    stream = WDResourceFactory.createInputStream(new FileInputStream(new File("<pathof the file to be download>")));
    catch(Exception e)
    return stream;
    also look at this thread  How to DownLoad any type of File from the server(PDF,XLS,Word)

  • How to download a file from the internet using terminal

    how to download a file from the internet using terminal
    does any one know how to download afile from the internet using the Terminal application?

    Use curl. Something like this:
    curl -O
    For more info, type +man curl+.

  • How to download a file from AL11 inot Excel format without collapse the col

    Please suggest how to download a file from AL11 to Excel sheet.currenlty all field are merging into single column.I writing this file via using DATASET.

       Try this code,
    TYPES : BEGIN OF ty_emp,
              empno(2) TYPE c,
              empid(10) TYPE c,
              empname(3) TYPE c,
            END OF ty_emp.
    DATA : it_emp TYPE TABLE OF ty_emp,
            wa_emp TYPE ty_emp.
    DATA : pbk TYPE string.
    PARAMETERS : p_file TYPE rlgrap-filename.
    PARAMETERS : p_asfile TYPE rlgrap-filename.
    pbk = p_file.
        READ DATASET p_asfile INTO wa_emp.
        IF sy-subrc <> 0.
        APPEND wa_emp TO it_emp.
    CLOSE DATASET p_asfile.
    Filling the already created file with download PS radiobutton
      BIN_FILESIZE                  =
          filename                      = pbk
      FILETYPE                      = 'ASC'
         append                        = 'X'
         write_field_separator         = ' '
      HEADER                        = '00'
      TRUNC_TRAILING_BLANKS         = ' '
      WRITE_LF                      = 'X'
      COL_SELECT                    = ' '
      COL_SELECT_MASK               = ' '
      DAT_MODE                      = ' '
      FILELENGTH                    =
          data_tab                      = it_emp
      FILE_WRITE_ERROR              = 1
      NO_BATCH                      = 2
      INVALID_TYPE                  = 4
      NO_AUTHORITY                  = 5
      UNKNOWN_ERROR                 = 6
      HEADER_NOT_ALLOWED            = 7
      SEPARATOR_NOT_ALLOWED         = 8
      FILESIZE_NOT_ALLOWED          = 9
      HEADER_TOO_LONG               = 10
      DP_ERROR_CREATE               = 11
      DP_ERROR_SEND                 = 12
      DP_ERROR_WRITE                = 13
      UNKNOWN_DP_ERROR              = 14
      ACCESS_DENIED                 = 15
      DP_OUT_OF_MEMORY              = 16
      DISK_FULL                     = 17
      DP_TIMEOUT                    = 18
      FILE_NOT_FOUND                = 19
      CONTROL_FLUSH_ERROR           = 21
      OTHERS                        = 22
      IF sy-subrc <> 0.

  • HT6154 how to download the files from mail like gmail or yahoo or hotmail to my iphone 5s.I have not seen the option in my iphone 5s

    how to download the files from mail like gmail or yahoo or hotmail to my iphone 5s.I have not seen the option in my iphone 5s

    Download what files?
    What is the actual problem that is occurring?

  • How to download .doc file from ms sql

    Hi guys.,,,!
    I have a problem in file uploading and downloading. The problem is i upload my .doc file in ms sql server successfully completed. After that i would like to download the file from the database.can anybody tell that how to download the file from the database.

    mani_miit wrote:
    I have a problem in file uploading and downloading.OK.
    The problem is i upload my .doc file in ms sql server successfully completed. Sorry, I don't see a problem here? You said that it is successfully completed. Please elaborate the problem.
    After that i would like to download the file from the database.can anybody tell that how to download the file from the database.Just get an inputstream of the file from the database using ResultSet#getBinaryStream() and write it to the output of whatever UI technology you're using.

  • How to download a file from a folder

    hello frnds.. i've uploaded a file to a folder in tomcat server. Now how to download that file at the client side.. pls help me out... it would be better if you gimme the related code for it..

    Create a link to it.
    Here I asked a similar question a while back. Link
    Edited by: gtRpr on 2008/12/15 10:08

  • Both my husband and I have our Macs backed up on Time Machine. I have a new Mac and want to download my files,etc. from Timeline to my new Mac. How do I ensure that Time Machine downloads only MY files, and not my husband's files?

    Both my husband and I have our MacBook Pros backed up to Time Machine. I have a new MacBook Pro and want to download my files, etc. from Time Machine to my new Mac. I do I ensure that Time Machine downloads only MY files to my new Mac, and not my husband's files?

    OS X uses a unique identifier so there will be no problems.

Maybe you are looking for

  • Error message when starting hotsync

    i always get the error message (sys0505) (0,841) i dont have any problems when i hotsync but this error message troubles me. please do help me. thank you  Post relates to: Palm TX

  • Problems copying and trashing files

    OK - here's what I assume are two seperate issues, or they may be related. (I'm running 10.3.9 on an iBook G4 and attempting to move files to a USB external). I have a DVD of jpg photos I was attempted to copy onto an external hard drive. About half

  • How do i take snapshot of desktop?

    Hi using java program i need to take the snapshot of my operating system's desktop and display it in the JFrame. So how do i take a snapshot of my desktop?

  • Cannot move my former .wma files to itunes for mac

    Over the years, I ripped all of my cds and stored them on my PC.  Because I was using a PC, I ripped this music in .WMA format.  When I got my macbook, I was EXTREMELY disappointed that I couldn't just transfer these files into itunes.  So I did some

  • Problem of Sync on Lite 10g

    Hi ppl, i have a problem with sincronization of Oracle Lite 10g (10.2) The problem exists when i use .NET to sincronize local Lite with the OAS in the syncerr.txt i obtain this : 2007/2/21 8:42:31 ..\..\ocapi\OkapiWriter.cpp Line:940 rc:-3264 And in