C# – Download von Dateien aus Sharepoint

Veröffentlicht von

Wie kann ich eine Datei aus Sharepoint herunterladen?

Download einer Datei

Download einer Datei aus Sharepoint.

Benötigt “NormalizeUrl“.

/// <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);
	}
}

Download einer älteren Version

Ältere Versionen einer Datei müssen gesondert behandelt werden.

Zuerst muss die URL umgewandelt werden, in die “normale” URL der Datei. Anschließend rufen wir damit die Versionsinformationen ab und können dann über die Versionen iterieren.

/// <summary>
/// Download a historical versioned document from Sharepoint
/// </summary>
/// <param name="link"></param>
/// <param name="targetDocument"></param>
public void DownloadHistoryFile(string link, string targetDocument)
{
	if (!SharepointHelper.IsHistoryLink(link)) throw new Exception("No sharepoint version link.");

	var targetVersion = SharepointHelper.GetVersionFromUrl(link);
	link = NormalizeUrl(link);
	var originalUrl = SharepointHelper.RemoveHistoryFromUrl(link);
	
	var file = _context.Web.GetFileByServerRelativeUrl(originalUrl);
	var fileVersions = file.Versions;
	_context.Load(file);
	_context.Load(fileVersions);
	_context.ExecuteQuery();

	foreach (var version in fileVersions)
	{
		if (version.ID == targetVersion)
		{
			var str = version.OpenBinaryStream();
			_context.ExecuteQuery();

			using (var fileStream = new FileStream(targetDocument, FileMode.OpenOrCreate))
			{
				str.Value.CopyTo(fileStream);
			}

			break;
		}
	}
}

SharepointHelper-Klasse

public class SharepointHelper
{
	/// <summary>
	/// returns the site url from the link, example:
	/// https://site.sharepoint.com/sites/Team/_layouts/15/Doc.aspx?OR=teams&amp;action=edit&amp;sourcedoc={89552B2A-00FB-4C4C-A6DF-AD6BEAB3BA25}";
	/// returns
	/// https://site.sharepoint.com/sites/Team/
	/// </summary>
	/// <param name="link"></param>
	/// <returns></returns>
	public static string GetSiteUrlFromLink(string link)
	{
		const string pattern = @"(?<siteurl>((http:\/\/|https:\/\/).*?\/.*?\/.*?\/))";
		var regex = new Regex(pattern);
		var match = regex.Match(link);

		if (match.Success)
		{
			var value = match.Groups["siteurl"].Value.Trim();
			return value;
		}

		return null;
	}

	/// <summary>
	/// Returns the relative URL from the link
	/// https://site.sharepoint.com/sites/Team/_layouts/15/Doc.aspx?OR=teams&amp;action=edit&amp;sourcedoc={89552B2A-00FB-4C4C-A6DF-AD6BEAB3BA25}";
	/// returns
	/// /sites/Team/_layouts/15/Doc.aspx?OR=teams&amp;action=edit&amp;sourcedoc={89552B2A-00FB-4C4C-A6DF-AD6BEAB3BA25}";
	/// </summary>
	/// <param name="link"></param>
	/// <returns></returns>
	public static string GetRelativeUrlFromLink(string link)
	{
		var index = link.IndexOf("/sites/", StringComparison.Ordinal);
		if (index != -1)
		{
			var result = link.Substring(index);
			return result;
		}

		return null;
	}

	/// <summary>
	/// Removes the history information from an url
	/// </summary>
	/// <param name="url"></param>
	/// <returns></returns>
	public static string RemoveHistoryFromUrl(string url)
	{
		const string pattern = @"_vti_history\/.*?\/";
		var regex = new Regex(pattern);
		var result = regex.Replace(url, "");
		return result;
	}

	/// <summary>
	/// Checks if the url is a history link from Sharepoint
	/// </summary>
	/// <param name="url"></param>
	/// <returns></returns>
	public static bool IsHistoryLink(string url)
	{
		var result = url.Contains("_vti_history");
		return result;
	}

	/// <summary>
	/// Extracts the version from a Sharepoint history url
	/// </summary>
	/// <param name="url"></param>
	/// <returns></returns>
	public static int GetVersionFromUrl(string url)
	{
		var pattern = @"_vti_history\/(?<version>.*?)\/";
		var regex = new Regex(pattern);
		var match = regex.Match(url);

		if (match.Success)
		{
			var versionString = match.Groups["version"].Value;
			var versionInt = Convert.ToInt16(versionString);
			return versionInt;
		}

		return -1;
	}

	/// <summary>
	/// Converts a sharepoint version to the readable major.minor format
	/// </summary>
	/// <param name="sharepointVersion">e.g. 518</param>
	/// <returns></returns>
	public static string SharepointVersionToMajorMinor(int sharepointVersion)
	{
		var remainder = sharepointVersion % 512;
		var major = sharepointVersion / 512;
		var version = major + "." + remainder;

		return version;
	}

	/// <summary>
	/// Converts a major.minor version information to the sharepoint version
	/// number
	/// </summary>
	/// <param name="version">e.g. 1.6</param>
	/// <returns></returns>
	public static int MajorMinorToSharepointVersion(string version)
	{
		var splitted = version.Split('.');
		if (splitted.Length != 2) return -1;

		var major = Convert.ToInt16(splitted[0]);
		var minor = Convert.ToInt16(splitted[1]);

		var result = major * 512 + minor;
		return result;
	}
}

Kommentar hinterlassen

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