2015-12-14 2 views
0

У меня есть консольное приложение, которое в конечном итоге будет запущено в качестве приложения консоли. Мне нужно пройти через внешний сайт Sharepoint, найти все новые элементы и посмотреть, есть ли какие-либо вложения, поэтому мне нужно загрузить эти вложения.Загрузка всех вложений в элемент SharePoint автоматически

Я могу запросить Список, и я могу выполнять итерацию через вложения, чтобы заполнить коллекцию файлов.

FolderToSaveTo разрешает «\\ APPDEV03 \ NEMStoPSIMS \» и передает оператор if (System.IO.Directory.Exists (destPath)), но на следующей строке использует (Stream destFile = System.IO.File.OpenWrite (DestPath)) бросает { «имя файла, имени папки или синтаксис метки тома неправильно. \ г \ п»}

Я могу перейти к \ APPDEV03 \ NEMStoPSIMS \ и я могу сохранить файл вручную.

<add key="FolderToSaveTo" value="\\APPDEV03\NEMStoPSIMS\" /> 

SharePointConnector.FolderToSaveTo = ConfigurationManager.AppSettings["FolderToSaveTo"]; 

     try 
     { 
      ClientContext context = new ClientContext(sp_site_address); 

      context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; 
      context.FormsAuthenticationLoginInfo = new 
             FormsAuthenticationLoginInfo(username, pwd); 

      List list = context.Web.Lists.GetByTitle(requests_list_name); 

      CamlQuery query = new CamlQuery(); 
      query.ViewXml = "<View><RowLimit>100</RowLimit></View>"; 

      ListItemCollection items = list.GetItems(query); 

      context.Load(list); 
      context.Load(items); 

      context.ExecuteQuery(); 

      foreach (ListItem oListItem in items) 
      {      

       FileCollection Files = GetAttachments(context, list, oListItem);      

       foreach (Microsoft.SharePoint.Client.File f in Files) 
       {       
        Download(f.ServerRelativeUrl, FolderToSaveTo, context); 
       } 

       lstRequests.Add(Agreement); 
      } 

     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 

    public static FileCollection GetAttachments(ClientContext ctx, List list, ListItem item) 
    {    
     ctx.Load(list, l => l.RootFolder.ServerRelativeUrl); 
     ctx.Load(ctx.Site, s => s.Url); 
     ctx.ExecuteQuery(); 

     Folder attFolder = ctx.Web.GetFolderByServerRelativeUrl(list.RootFolder.ServerRelativeUrl + "/Attachments/" + item.Id); 
     FileCollection files = attFolder.Files; 

     ctx.Load(files, fs => fs.Include(f => f.ServerRelativeUrl, f => f.Name, f => f.ServerRelativeUrl)); 
     ctx.ExecuteQuery(); 

     return files; 

    } 

    public static void Download(string serverFilePath, string destPath, ClientContext context) 
    { 
     using (FileInformation ffl = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, serverFilePath)) 
     { 
      if (System.IO.Directory.Exists(destPath)) 
      { 
       using (Stream destFile = System.IO.File.OpenWrite(destPath)) 
       { 
        byte[] buffer = new byte[8 * 1024]; 
        int len; 
        while ((len = ffl.Stream.Read(buffer, 0, buffer.Length)) > 0) 
        { 
         destFile.Write(buffer, 0, len); 
        } 
       } 

      } 

     } 
    } 

ответ

2

Я проверил этот код без форм. Я передал имя файла как переменную функции загрузки и полностью переписал поток в часть файла и внес несколько незначительных корректировок в вызовы SharePoint. Прекрасно работает.

static void Main(string[] args) 
    { 
     using (ClientContext context = new ClientContext(sp_site_address)) 
     { 
      context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; 
      context.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(username, pwd); 

      List list = context.Web.Lists.GetByTitle(requests_list_name); 
      CamlQuery query = new CamlQuery(); 
      query.ViewXml = "<View><RowLimit>100</RowLimit></View>"; 
      ListItemCollection items = list.GetItems(query); 
      context.Load(items); 
      context.ExecuteQuery(); 

      foreach (ListItem oListItem in items) 
      { 
       FileCollection files = GetAttachments(context, list, oListItem); 
       foreach (Microsoft.SharePoint.Client.File f in files) 
       { 
        Download(f.ServerRelativeUrl, FolderToSaveTo, context, f.Name); 
       } 
       lstRequests.Add(Agreement); 
      } 
     } 
    } 

    public static FileCollection GetAttachments(ClientContext ctx, List list, ListItem item) 
    { 
     ctx.Load(list, l => l.RootFolder.ServerRelativeUrl); 
     ctx.Load(ctx.Site, s => s.Url); 
     ctx.ExecuteQuery(); 

     Folder attFolder = ctx.Web.GetFolderByServerRelativeUrl(list.RootFolder.ServerRelativeUrl + "/Attachments/" + item.Id); 
     FileCollection files = attFolder.Files; 

     ctx.Load(files, fs => fs.Include(f => f.ServerRelativeUrl, f => f.Name, f => f.ServerRelativeUrl)); 
     ctx.ExecuteQuery(); 

     return files; 

    } 

    public static void Download(string serverFilePath, string destPath, ClientContext context, string filename) 
    { 
     using (FileInformation ffl = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, serverFilePath)) 
     { 
      if (System.IO.Directory.Exists(destPath)) 
      { 
       using (FileStream fileStream = System.IO.File.Create(destPath + "\\" + filename)) 
       { 
        using (MemoryStream stream = new MemoryStream()) 
        { 
         ffl.Stream.CopyTo(stream); 
         stream.WriteTo(fileStream); 
        } 
       } 
      } 
     } 
    } 
+0

Это абсолютно сработало. Thanx очень много !! –

Смежные вопросы