从SharePoint读取文件未返回正确值

时间:2019-06-03 08:04:01

标签: c# file sharepoint csom

我正在使用以下代码从sharepoint 2019读取文件,并且返回值不是字符串。返回值示例:0 \ 0 \ 0(\ u0001 \ 0 \ 0 \ u001e \ 0 \ 0 \ 0 \ 0 \ 0 \ 0

using (ClientContext clientContext = new ClientContext("http://sharepoint2019/sites/test/"))
        {
            KeywordQuery keywordQuery = new KeywordQuery(clientContext);
            keywordQuery.QueryText = "SharePoint";
            keywordQuery.EnablePhonetic = true;
            SearchExecutor searchExecutor = new SearchExecutor(clientContext);                
            ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
            clientContext.ExecuteQuery();
            foreach (var resultRow in results.Value[0].ResultRows)
            {
                Console.WriteLine("{0}: {1} ({2})", resultRow["Title"], resultRow["Path"], resultRow["Write"]);

                File file= clientContext.Web.GetFileByUrl(resultRow["Path"].ToString());
                var stream = file.OpenBinaryStream();
                clientContext.Load(file);
                clientContext.ExecuteQuery();

                FileInformation fileInformation = File.OpenBinaryDirect(clientContext, (string)file.ServerRelativeUrl);
                using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
                {
                    // Read the stream to a string, and write the string to the console.
                   String line = sr.ReadToEnd();
                    Console.WriteLine(line);
                }


            }

        }

1 个答案:

答案 0 :(得分:1)

如果您正在读取Word等文件(不是txt文件),则需要使用Open Xml库读取Word中的字符串,文件流无法按预期返回真实字符串:

Get Plain Text of a Word Document using Open XML (CSOpenXmlGetPlainText)

Open a word processing document from a stream (Open XML SDK)