我收到此异常-属性或字段“ ServerRelativeUrl”尚未初始化

时间:2019-05-23 17:42:44

标签: c# sharepoint-online

我正在尝试上传在C#中运行时生成的文件,但出现以下异常。

属性或字段“ ServerRelativeUrl”尚未初始化。尚未请求或尚未执行请求。可能需要明确要求。

我也在使用SharePoint CSOM和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();
}                                  

2 个答案:

答案 0 :(得分:0)

在RootFolder类中创建一个初始化方法,您可以在其中初始化变量

public RootFolder()
{
    ServerRelativeUrl = string.Empty;
}

或将ServerRelativeUrl更改为自动属性

public string ServerRelativeUrl{set;get;}

答案 1 :(得分:0)

收到此消息的原因是因为尚未加载Rootfolder。为了使用它,将以下内容放入:

var library = ctx.Web.Lists.GetByTitle("testtest");
ctx.Load(library.RootFolder);
ctx.ExecuteQuery();