Reputation:
I'm trying to upload a file generated at runtime in C# but I got below exception.
The property or field 'ServerRelativeUrl' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
I'm also using SharePoint CSOM and Microsoft.SharePoint.Client
using (var ctx = new ClientContext(siteUrl))
{
try
{
ctx.Credentials = SPOCredentials;
ctx.ExecuteQuery();
}
catch(ClientRequestException)
{
ctx.Credentials = SPCredentials;
ctx.ExecuteQuery();
}
catch(NotSupportedException)
{
ctx.Credentials = SPCredentials;
ctx.ExecuteQuery();
Console.WriteLine("SharePoint On-Premise");
}
var library = ctx.Web.Lists.GetByTitle("testtest");
var fileBytes = new byte[] { };
fileBytes = ReadData();
//Information about the file
var fileInformation = new FileCreationInformation
{
//Server relative url of the document
Url = library.RootFolder.ServerRelativeUrl + "/file.pdf",
//Overwrite file if it's already exist
Overwrite = true,
//Content fo the file
Content = fileBytes
};
//Upload the file to root folder of the Document library
library.RootFolder.Files.Add(fileInformation);
ctx.Load(library);
ctx.ExecuteQuery();
}
Upvotes: 2
Views: 5940
Reputation: 156
The reason you get this message is because you haven't loaded the Rootfolder. In order to use it, put the following in:
var library = ctx.Web.Lists.GetByTitle("testtest");
ctx.Load(library.RootFolder);
ctx.ExecuteQuery();
Upvotes: 5
Reputation: 149
In your RootFolder class create an initialization method where you initialize the variable
public RootFolder()
{
ServerRelativeUrl = string.Empty;
}
OR change your ServerRelativeUrl to a autoproperty
public string ServerRelativeUrl{set;get;}
Upvotes: -1