0

i need to write a C# code that can connect to my sharePoint and get all the documents and also upload some new document.

I can't find any simple example code that can do it

any help please ..

Thanks

1 Answer 1

1
static void Main(string[] args) {  
    var site = new ClientContext("http://sitename/");  
    var web = site.Web;  
    site.Load(web);  
    site.ExecuteQuery();  
    // Library name - Shared Documents  
    List list = web.Lists.GetByTitle("Shared Documents");  
    site.Load(list);  
    site.ExecuteQuery();  
    site.Load(list.RootFolder);  
    site.ExecuteQuery();  
    site.Load(list.RootFolder.Folders);  
    site.ExecuteQuery();  
    processFolderClientobj(list.RootFolder.ServerRelativeUrl);  
    foreach(Folder folder in list.RootFolder.Folders) {  
        processFolderClientobj(folder.ServerRelativeUrl);  
    }  
}  
public static void processFolderClientobj(string folderURL) {  
    string Destination = @  
    "c:\\temp";  
    var site = new ClientContext("http://sitename/");  
    var web = site.Web;  
    site.Load(web);  
    site.ExecuteQuery();  
    Folder folder = web.GetFolderByServerRelativeUrl(folderURL);  
    site.Load(folder);  
    site.ExecuteQuery();  
    site.Load(folder.Files);  
    site.ExecuteQuery();  
    foreach(Microsoft.SharePoint.Client.File file in folder.Files) {  
        string destinationfolder = Destination + "/" + folder.ServerRelativeUrl;  
        Stream fs = Microsoft.SharePoint.Client.File.OpenBinaryDirect(site, file.ServerRelativeUrl).Stream;  
        byte[] binary = ReadFully(fs);  
        if (!Directory.Exists(destinationfolder)) {  
            Directory.CreateDirectory(destinationfolder);  
        }  
        FileStream stream = new FileStream(destinationfolder + "/" + file.Name, FileMode.Create);  
        BinaryWriter writer = new BinaryWriter(stream);  
        writer.Write(binary);  
        writer.Close();  
    }  
}  
public static byte[] ReadFully(Stream input) {  
    byte[] buffer = new byte[16 * 1024];  
    using(MemoryStream ms = new MemoryStream()) {  
        int read;  
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0) {  
            ms.Write(buffer, 0, read);  
        }  
        return ms.ToArray();  
    }  
}  

Ref here for PowerShell and SharePoint Object Model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.