Zugriff mit C# auf Sharepoint – CodeSnippets

Veröffentlicht von

Wie kann ich mit C# auf Sharepoint zugreifen.

Authentifizierung

Der erste Schritt ist die Anmeldung am Sharepoint-Server:

using Microsoft.SharePoint.Client;
using File = Microsoft.SharePoint.Client.File;


/// <summary>
/// Authenticate with the Sharepoint site
/// </summary>
public bool Authenticate()
{
	var authManager = new OfficeDevPnP.Core.AuthenticationManager();
	var context = authManager.GetWebLoginClientContext("https://company.sharepoint.com/sites/TestTeam/");
	var result = _context != null;	
	return result;
}

Sharepoint Urls

Arbeitet man mit Sharepoint bekommt man es immer wieder mit verschiedenen URLS zu tun. Die folgende Methode wandelt die URL entsprechend um, sodass z.B. ein Dateidownload einfach erfolgen kann. In den meisten Fällen enthält eine URL die Guid des Dokuments, welche wir dann in einen direkten Link umwandeln.

/// <summary>
/// Return an URL which should work for most scenarios, for example generated URLs from
/// teams will not work in certain scenarios
/// </summary>
/// <param name="url"></param>
public string NormalizeUrl(string url)
{
	Match GetMatch(string pattern)
	{
		var regex = new Regex(pattern);
		var match = regex.Match(url);
		return match;
	}


	//do not get relative URL for teams links, only for sharepoint
	if (!url.StartsWith("https://teams.microsoft.com"))
	{
		url = SharepointHelper.GetRelativeUrlFromLink(url);
	}

	/*
	 * support for "/sites/TestTeam/_layouts/15/Doc.aspx?OR=teams&action=edit&sourcedoc={89552B2A-00FB-4C4C-A6DF-AD6BEAB3BA25}";
	 * in that case we extract the guid and get the files server relative url and return it
	 */
	{
		const string pattern = "sourcedoc={(?<guid>.*)}";
		var match = GetMatch(pattern);
		if (match.Success)
		{
			var guidString = match.Groups["guid"].Value.Trim();
			url = GetFileUrlFromGuid(guidString);
			return url;
		}
	}

	/*
	 * Support for sharepoint browser links
	 *https://company.sharepoint.com/:w:/r/sites/TestTeam/_layouts/15/Doc.aspx?sourcedoc=%7B89552B2A-00FB-4C4C-A6DF-AD6BEAB3BA25%7D&file=TestDoc.docx&action=default&mobileredirect=true";
	 */
	{
		const string pattern = "sourcedoc=%7B(?<guid>.*?)%";
		var match = GetMatch(pattern);
		if (match.Success)
		{
			var guidString = match.Groups["guid"].Value.Trim();
			url = GetFileUrlFromGuid(guidString);
			return url;
		}
	}

	/*
	 * Support for Microsoft teams url
	 */
	{
		const string pattern = @"\/file\/(?<guid>.*)\?";
		var match = GetMatch(pattern);
		if (match.Success)
		{
			var guidString = match.Groups["guid"].Value.Trim();
			url = GetFileUrlFromGuid(guidString);
			return url;
		}
	}

	return url;
}

Datei-URL einer Guid ermitteln

Die folgende Funktion ermittelt anhand einer Guid den Dateilink von Sharepoint.

/// <summary>
/// Returns the file URL for the given Guid
/// </summary>
/// <param name="guidString"></param>
/// <returns></returns>
public string GetFileUrlFromGuid(string guidString)
{
	var guid = Guid.Parse(guidString);
	var file = _context.Web.GetFileById(guid);
	_context.Load(file);
	_context.ExecuteQuery();
	var url = file.ServerRelativeUrl;
	return url;
}

Download einer Datei von Sharepoint

/// <summary>
/// Downloads a file from sharepoint
/// </summary>
/// <param name="link"></param>
/// <param name="targetDocument"></param>
public void DownloadFile(string link, string targetDocument)
{
	var relativeUrl = NormalizeUrl(link);
	var fileInfo = File.OpenBinaryDirect(_context, relativeUrl);
	
	using (Stream destination = System.IO.File.Create(targetDocument))
	{
		for (var a = fileInfo.Stream.ReadByte(); a != -1; a = fileInfo.Stream.ReadByte())
			destination.WriteByte((byte)a);
	}
}

2 Kommentare

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.