的一點是,ClientContext constructor接受網頁/網站的URL 只 但是,如果URL將以下列格式指定:
http://site/web/documents/file.docx
然後將發生異常System.Net.WebException
。
下面的例子演示瞭如何從請求URL解析ClientContext
:
public static class ClientContextUtilities
{
/// <summary>
/// Resolve client context
/// </summary>
/// <param name="requestUri"></param>
/// <param name="context"></param>
/// <param name="credentials"></param>
/// <returns></returns>
public static bool TryResolveClientContext(Uri requestUri, out ClientContext context, ICredentials credentials)
{
context = null;
var baseUrl = requestUri.GetLeftPart(UriPartial.Authority);
for (int i = requestUri.Segments.Length; i >= 0; i--)
{
var path = string.Join(string.Empty, requestUri.Segments.Take(i));
string url = string.Format("{0}{1}", baseUrl, path);
try
{
context = new ClientContext(url);
if (credentials != null)
context.Credentials = credentials;
context.ExecuteQuery();
return true;
}
catch (Exception ex) {}
}
return false;
}
}
使用
ClientContext context;
if (ClientContextUtilities.TryResolveClientContext(requestUri, out context, null))
{
using (context)
{
var baseUrl = requestUri.GetLeftPart(UriPartial.Authority);
var fileServerRelativeUrl = requestUri.ToString().Replace(baseUrl, string.Empty);
var file = context.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl);
context.Load(file);
context.Load(context.Web);
context.Load(context.Site);
context.ExecuteQuery();
}
}
因爲你的目標是要下載的文件,則是非常簡單的方式在不解析url部分的情況下完成它。
例如,使用WebClient.DownloadFile Method://服務器/否/否/這裏:
private static void DownloadFile(Uri fileUri, ICredentials credentials, string localFileName)
{
using(var client = new WebClient())
{
client.Credentials = credentials;
client.DownloadFile(fileUri, localFileName);
}
}
如果將根網站集URI是_http工作的?下載更好!但在允許下載之前需要先檢查一些列。 – edelwater 2015-04-03 14:11:58
它應該,至少我從來沒有經歷過任何問題,不管它是否根網站收集或沒有 – 2015-04-03 14:18:17