Share via

SharePoint Online Load Shared File

SvenGlöckner 446 Reputation points
2022-04-08T10:35:17.113+00:00

Hi,

I'm trying to load a shared file from SharePoint Online using C# SDK.
The shared file link is: https://contoso-my.sharepoint.com/:x:/g/personal/j_doe_contoso_com/EUehCbQDphRGnPdkftCKoj4B-JXkrG92E64DIgIJxiRqPA

When using web.GetFileByUrl I'm getting a 404 error.
My code is:

var web = ctx.Web;
                var file = web.GetFileByUrl("https://contoso-my.sharepoint.com/:x:/g/personal/j_doe_contoso_com/EUehCbQDphRGnPdkftCKoj4B-JXkrG92E64DIgIJxiRqPA");
                ctx.Load(file);
                ctx.ExecuteQuery();
Microsoft 365 and Office | SharePoint | Development
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments

Answer accepted by question author

RaytheonXie_MSFT 40,496 Reputation points Microsoft External Staff
2022-04-11T06:07:58.72+00:00

Hi @SvenGlöckner ,
web.GetFileByUrl doesn't work with share link. The url should be like https://contoso.sharepoint.com/sites/abc/document/test.txt. If you want to access share link. Please try following code.

var uri = $"https://xxx.sharepoint.com/:i:/s/blah/funkyShareurlhere?e=somestuffhere&download=1";  
var handler = new HttpClientHandler {AllowAutoRedirect = false, UseCookies = true};  
while (true)  
{  
    var request = new HttpRequestMessage(HttpMethod.Post, uri);  
    var response = new HttpClient(handler).SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();  
    var statusCode = (int) response.StatusCode;  
  
    if (statusCode >= 300 && statusCode <= 399)  
    {  
        var redirectUri = response.Headers.Location;  
        if (!redirectUri.IsAbsoluteUri)  
        {  
            redirectUri = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority) + redirectUri);  
        }  
  
        uri = redirectUri.AbsoluteUri;  
        continue;  
    }  
  
    if (response.IsSuccessStatusCode)  
    {  
        var data = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();  
    }  
}  

If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.