I was searching how to upload a document into a document library adding some fields. But I haven't find anything with the client object model.
Then I have to make my own functions where first of all I upload the file and then I search for the file and update his fields.
{
string attachedFile = @"C:\\test\\test.docx";
string spFilepath = UploadFile(attachedFile);
SetFileFields(spFilepath);
Console.Write("Press any key to exit...");
Console.ReadLine();
}
public static string UploadFile(string attachFilePath)
{
ClientContext clientContext = new ClientContext("http://mysite/");
clientContext.Credentials = new NetworkCredential("user", "pass");
List l = clientContext.Web.Lists.GetByTitle("listTitle");
Folder f = l.RootFolder;
clientContext.Load(f);
clientContext.ExecuteQuery();
string spFilepath = string.Empty;
using (FileStream strm = new FileInfo(attachFilePath).Open(FileMode.Open))
{
spFilepath = Combine(f.ServerRelativeUrl, Path.GetFileName(attachFilePath));
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, spFilepath, strm, true);
}
clientContext.ExecuteQuery();
return spFilepath;
}
public static void SetFileFields(string spFilepath)
{
ClientContext clientContext = new ClientContext("http://mysite/");
clientContext.Credentials = new NetworkCredential("user", "pass");
List l = clientContext.Web.Lists.GetByTitle("listTitle");
FileCollection fc = l.RootFolder.Files;
clientContext.Load(fc, files => files
.Include(
file => file.Name,
file => file.ServerRelativeUrl)
.Where(file => file.ServerRelativeUrl == spFilepath )
);
clientContext.ExecuteQuery();
if (fc.Count > 0)
{
Microsoft.SharePoint.Client.File file = fc[0];
ListItem listItem = file.ListItemAllFields;
listItem["field1"] = 2;
listItem["field2"] = "value2";
listItem["field3"] = DateTime.Now;
listItem["field4"] = "value3";
listItem.Update();
}
clientContext.ExecuteQuery();
}
static string Combine(string baseUrl, string relativeUrl)
{
string cleanBaseUrl = baseUrl.Replace("\\", "/");
string cleanRelativeUrl = relativeUrl.Replace("\\", "/");
cleanBaseUrl = cleanBaseUrl.TrimEnd(new char[] { '/' });
cleanRelativeUrl = cleanRelativeUrl.TrimStart(new char[] { '/' });
return string.Format("{0}/{1}", cleanBaseUrl, cleanRelativeUrl);
}
Please if someone knows a better way or the microsoft way I'll be glad to read your code in the comments