The following code snippet can be used to upload a file from ASP.NET web page to SharePoint 2007 document libarary.
To use this code, the user account should have read/write access in the SharePoint document Libarary.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPage3.aspx.cs" Inherits="TestPage3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table width="100%"> <tr> <td> <asp:ValidationSummary ID="ValidationSummary1" runat="server" /> </td> </tr> <td> <input id="fileUploade1" type="file" runat="server"/><asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" /> <asp:CustomValidator ID="CustomValidator1" runat="server">*</asp:CustomValidator> </td> </tr>
<tr> <td> </td> </tr> </table> </div> </form> </body> </html>
In the following server side, The selected file can be uploaded by clicking the Upload button.
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.SharePoint; public partial class TestPage : System.Web.UI.Page { protected void btnUpload_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(fileUploade1.PostedFile.FileName)) {
CustomValidator1.ErrorMessage = "Browse and select a file to be uploaded"; CustomValidator1.IsValid = false; return; }
string[] fileName = fileUploade1.PostedFile.FileName.Split('\\'); int length = fileName.Length; if (String.IsNullOrEmpty(fileName[length - 1].Trim())) return; string uploadFileName = fileName[length - 1];
//Change sharepoint site name and port number as you needed SPSite spSite = new SPSite("http://yoursharepointsite:32456/yoursharepointDocLibSite/"); SPWeb spWeb = spSite.OpenWeb();
spWeb.AllowUnsafeUpdates = true; SPFolder folder = spWeb.GetFolder("myDocumentLibraryFolder"); SPFileCollection spFiles = folder.Files;
System.IO.Stream fStream = fileUploade1.PostedFile.InputStream; byte[] MyData = new byte[fStream.Length]; fStream.Read(MyData, 0, (int)fStream.Length); fStream.Close(); SPFile spFile = spFiles.Add(uploadFileName, MyData, true); spWeb.AllowUnsafeUpdates = false;
} }
|
| Author: Ashish Sharma 13 Aug 2009 | Member Level: Bronze Points : 1 |
List all the reference file with your article, I did'nt find any reference for using System.Linq;
|
| Author: Ramesh S 13 Aug 2009 | Member Level: Gold Points : 1 |
I didn't use System.Linq in this code snippet. It was added by default when I created a new project. Now I have removed that reference.
|