You probably seen something similar to what I’m about to show you all over the internet. I will be using the Copy Web Service. This service is used to add or copy files from disparate SharePoint sites to other sites or can be used to simply upload files to your SharePoint libraries.
Information about this service can be found here http://msdn.microsoft.com/en-us/library/copy(office.12).aspx
Here is a simple code snippet that will upload a file you’ve selected from the Open File Dialog we all use everyday. I’ve written this inside of a WPF application. You will need to reference the Copy Service and erase or comment some lines in order for you to use it in your application.
The code above does the following
a. Gets a reference to the Copy Service (in Visual Studio Web References)
b. Passes a set of credentials. Here, I use Network Credentials – http://msdn.microsoft.com/en-us/library/system.net.networkcredential.aspx
c. I subscribe to the Completed Event
d. Open a new File Dialog so I can select the file to upload
e. Get a FileInfo reference to the File I’ll be working with
f. Set my destination URL. This includes my SharePoint site + Library + File name. I use the SafeFileName property to get the extension of the file along with its name
g. I go ahead and read the stream of bytes till I reach the end. I do this read using the FileStream.Read operation. This will allow me to Write the bytes I ‘m reading into a buffer. More info on this can be found here. http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx
h. The FieldInformation class array is simply empty here. I don’t do much with it. I usually use this if I want to keep my metadata intact on the file
Till next time, take it easy!