This code sample will show how to upload a file from your local pc to Sharepoint site using object mode:
1. Create a project and import namespaces :
using System.IO;
using Microsoft.SharePoint;
2. The UploadFile funtion code:
public void UploadFile(string srcUrl, string destUrl)
{
if (! File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}
SPWeb site = new SPSite(destUrl).OpenWeb();
FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
}
The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of the destination. A System.IO.FileStream object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.
To upload a file from a local folder on the same server that is running Windows SharePoint Services, you can use a System.IO.FileStream object instead. In this case, add a using directive for the System.IO namespace, in addition to directives for System and Microsoft.SharePoint. The following example uses the Click event handler to call an UploadFile method, which in turn calls the previously described EnsureParentFolder method.
1 comment:
ohhho its really great article.Very useful
Post a Comment