简体   繁体   中英

Open and Read a text file Located in a SharePoint Document Library using CSOM

I'm able to get the relative path to a file in SharePoint. I now need to open the file and read its contents. This is where I'm stuck. I don't know how to open a file for reading unless it is local to my hard drive, which it is not. Here is my code:

If item.FieldValues("File_x0020_Type") = "html" Then
    Dim the_file As SP.File = oWebsite.GetFileByServerRelativeUrl(item.FieldValues("FileRef"))
    Dim reader As StreamReader = New StreamReader(the_file)  
    Dim sr As StreamReader = StreamReader(the_file)
    textbox1.text = sr.ReadToEnd()
    reader.Close()
End If

Sorry misread that.

ClientContext clientContext = new ClientContext("http://SpSiteUrl");
clientContext.ExecuteQuery();
FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, "thisFile");

System.IO.Stream stream = fileInfo.Stream;

using (StreamReader r = new StreamReader(stream))
     string line;
     while((line = file.ReadLine()) != null)
     {
         System.Console.WriteLine (line);  
     }
}

Once it is set to the Stream, you should be able to loop through it normally.

I also saw this second method.

using (var clientContext = new ClientContext(url))  {
    Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, "thisFile");
    using (var fileStream = System.IO.File.Create(getItem))
     {                  
        fileInfo.Stream.CopyTo(fileStream);
     }
}

Then you would just loop through the fileStream normally as well.

Here is a second way to loop as well -

using (StreamReader sr = new StreamReader(stream)) 
{
      while (sr.Peek() >= 0) 
      {
             Console.WriteLine(sr.ReadLine());
      }
}

And actually, now that I am reading your question one more time - you might be able to do just this.

Dim reader As StreamReader = New StreamReader(stream)  
textbox1.text = reader.ReadToEnd()
reader.Close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM