Sunday, November 13, 2011

Upload a File to a SharePoint Site from a Local Folder


Aspx Page

<form id="Form1" method="post" runat="server">
   <SharePoint:FormDigest runat="server" />
   <input id="File1" type="file" runat="server" title="upldFileBox">
   <asp:Button id="Button1" runat="server" 
      Text="Upload File"></asp:Button>
   <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
</form>

Code Behind

using System.IO;
using Microsoft.SharePoint;
if (File1.PostedFile == null)
    return;

string destUrl = TextBox1.Text;

SPWeb site = new SPSite(destUrl).OpenWeb();

Stream fStream = File1.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];

fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close(); 

EnsureParentFolder(site, destUrl);

site.Files.Add(destUrl, contents);


public string EnsureParentFolder(SPWeb parentSite, string destinUrl)
{
    destinUrl = parentSite.GetFile(destinUrl).Url;

    int index = destinUrl.LastIndexOf("/");
    string parentFolderUrl = string.Empty;

    if (index > -1)
    {
        parentFolderUrl = destinUrl.Substring(0, index);

        SPFolder parentFolder 
            = parentSite.GetFolder(parentFolderUrl);

        if (! parentFolder.Exists)
        {
            SPFolder currentFolder = parentSite.RootFolder;

            foreach(string folder in parentFolderUrl.Split('/'))
            {
                currentFolder 
                    = currentFolder.SubFolders.Add(folder);
            }
        }
    }
    return parentFolderUrl;
}

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);
}


No comments:

Post a Comment

Thank you for Commenting Will reply soon ......

Featured Posts

Installing vim openssh server openssh client build essential net tools i...

Installing Essential Packages in Ubuntu: `vim`, `opensshserver`, `opensshclient`, `buildessential`, and `nettools` When working on an Ubuntu...