Today, I’d like to show you how to create item in SharePoint2010 document library using SharePoint Web service. Originally, I thought I could use the WebSvcLists(list.asmx) that provides methods for working with lists and list data. However, after a bit Googling , I realize that I need to use the WebSvcCopy (copy.asmx).Here are the code used
private const string siteUrl = "http://ybbest";
private static void Main(string[] args)
{
using (CopyWSProxyWrapper copyWSProxyWrapper = new CopyWSProxyWrapper(siteUrl))
{
copyWSProxyWrapper.UploadFile("TestDoc2.pdf",
new[] {string.Format("{0}/Shared Documents/TestDoc2.pdf", siteUrl)},
Resource.TestDoc, GetFieldInfos().ToArray());
}
}
private static List<FieldInformation> GetFieldInfos()
{
var fieldInfos = new List<FieldInformation>();
//The InternalName , DisplayName and FieldType are both required to make it work
fieldInfos.Add(new FieldInformation
{
InternalName = "Title",
Value = "TestDoc2.pdf",
DisplayName = "Title",
Type = FieldType.Text
});
return fieldInfos;
}
Here is the code for the proxy wrapper.
public class CopyWSProxyWrapper : IDisposable
{
private readonly string siteUrl;
public CopyWSProxyWrapper(string siteUrl)
{
this.siteUrl = siteUrl;
}
private readonly CopySoapClient proxy = new CopySoapClient();
public void UploadFile(string testdoc2Pdf, string[] destinationUrls, byte[] testDoc,
FieldInformation[] fieldInformations)
{
using (CopySoapClient proxy = new CopySoapClient())
{
proxy.Endpoint.Address = new EndpointAddress(String.Format("{0}/_vti_bin/copy.asmx", siteUrl));
proxy.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
proxy.ClientCredentials.Windows.AllowedImpersonationLevel =
TokenImpersonationLevel.Impersonation;
CopyResult[] copyResults = null;
try
{
proxy.CopyIntoItems(testdoc2Pdf,
destinationUrls,
fieldInformations, testDoc, out copyResults);
}
catch (Exception e)
{
System.Console.WriteLine(e);
}
if (copyResults != null) System.Console.WriteLine(copyResults[0].ErrorMessage);
System.Console.ReadLine();
}
}
public void Dispose()
{
proxy.Close();
}
}
You can download the source code here .
******Update**********
It seems to be a bug that , you can not set the contentType when create a document item using Copy.asmx. In sp2007 the field type was Choice, however, in sp2010 it is actually Computed. I have tried using the Computed field type with no luck. I have also tried sending the ContentTypeId and this does not work.You might have to write your own web services to handle this.You can check my previous blog on how to get started with you own custom WCF in SP2010 here.
References:
SharePoint 2010 Web Services
SharePoint2007 Web Services
SharePoint MSDN Forum