I need to create a file in document library using CSOM, It is not like uploading a file from our local system. It should be created using code and uploaded to sharepoint library.
Is it possible?
I need to create a file in document library using CSOM, It is not like uploading a file from our local system. It should be created using code and uploaded to sharepoint library.
Is it possible?
You need to use the FileCreationInformation
to create a file.
Try the below code:
FileCreationInformation createFile = new FileCreationInformation();
createFile.Url = "test.txt";
//use byte array to set content of the file
string somestring = "hello there";
byte[] toBytes = Encoding.ASCII.GetBytes(somestring);
createFile.Content = toBytes;
List spList = context.Web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File addedFile = spList.RootFolder.Files.Add(createFile);
context.Load(addedFile);
context.ExecuteQuery();
ListItem item = addedFile.ListItemAllFields;
item["Title"] = "File generated using Code";
item.Update();
ctx.Load(item);
ctx.ExecuteQuery();
Console.WriteLine("File generated using code");
You can create a file in memory and save that to your document library.
var clientContext = new ClientContext("https://my.sharepoint.com/");
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine("Dummy text");
writer.Flush();
stream.Position = 0;
var fileUrl = "/Documents/MyDummyFile.txt";
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, stream, true);
}
}
Key here is the SaveBinaryDirect
method. More info on https://msdn.microsoft.com/en-us/library/ee538285
Try This
public static void UploadLogFileIntoDocumentLibrary(ClientContext ctx, Web oweb, string FilePath,string FileName)
{
try
{
#region Create File in Site Asset > Visitor Logs folder
//Get Server Relative URL of SiteAssets and Hit to Visitor Logs folder
Folder oFolder = oweb.GetFolderByServerRelativeUrl("/SiteAssets/Visitor Logs");
//Create a file
FileCreationInformation oCreateFile = new FileCreationInformation();
oCreateFile.Content = System.IO.File.ReadAllBytes(FilePath);
oCreateFile.Url = FileName;
oCreateFile.Overwrite = true;
//Add a created file to Given path
Microsoft.SharePoint.Client.File fileToUpload = oFolder.Files.Add(oCreateFile);
ctx.Load(fileToUpload);
ctx.ExecuteQuery();
//Delete the Temp created file
System.IO.File.Delete(FilePath);
#endregion
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
Here i am uploading text file inside the Folder so if its not required u can remove the Visitor Logs folder name