简体   繁体   中英

WCF streaming from Sharepoint

My custom WCF service has a method for downloading a file from a Sharepoint site. The goal is to call DownloadFile and then receive a stream.

[OperationContract]
Stream DownloadFile( string uri );

The code for fetching the file from Sharepoint and return the Stream is:

public Stream DownloadFile( string uri )
{
    // NOTE! we cannot use a using statement as the stream will get closed.
    var site = new SPSite( uri );
    var web = site.OpenWeb();
    var file = web.GetFile( uri );

    // some custom authentication code...

    // NOTE! do not close stream as we are streaming it.
    return file.OpenBinaryStream();
}

I guess the stream that gets streamed will automatically get properly closed and disposed by the WCF service as the streaming is complete?

But, how am I supposed to solve the problem with my sharepoint objects that are not disposed properly (site and web)? Will this be a problem in the long run? Is there any other approach available? I do not want to use the Sharepoint Client Object Model as I have some custom authentication code that needs to execute when downloading the file from Sharepoint.

Any thoughts or ideas that could point me in right direction?

UPDATE:

I might have resolved this by using the OperationCompleted event on current OperationContext like this:

OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += delegate
                                    {                                                                  
                                        if( stream != null )                                                                                                  
                                            stream.Dispose();
                                        site.Close();
                                        web.Close();
                                    };

Maybe I don't need to dispose the stream? Does anyone see something faulty with the above approach?

The above should be fine as long as you still have a reference to the SPSite and SPWeb then you can dispose of them.

Just a small one, best practice is to called Dispose() instead of Close() on the SPSite and SPWeb objects.

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