In this exemple, I will show you how to upload a file to a document library and how to link information to the uploaded file.
According that we have an <asp:FileUpload ID="FileUpload1" runat="server" /> in an aspx page that contains the file path that we want to upload.
1. Open a stream and save the file to an array of bytes.
Stream myStream = FileUpload1.PostedFile.inputStream;
byte[] bytes = new byte[Convert.ToInt32(FileUpload1.PostedFile.ContentLength)];
myStream.Read(bytes, 0, byt.Length);
myStream.Close();
2. Get a document library object and add the file to them.
SPFolder myLibrary = myWeb.Folders["DocumentLibraryName"];
SPFile myFile = myLibrary.Files.Add(myLibrary.ServerRelativeUrl + "/" + FileUpload1.FileName, bytes, false);
3. Update document library.
myLibrary.Update();
Now if you have to add file meta data to the upload file proceed as following.
1. Get the SPListItem relative to the uploaded file and save information.
SPListItem Item = myFile.Item;
Item["ColumnName"] = "my value";
2. Update the item.
Item.Update();
The entire code will look like:
using Microsoft.SharePoint;
using System;
using System.IO;
using System.Web.UI.WebControls;
namespace CDG
{
class Exemple
{
protected FileUpload FileUpload1;
public void foo_method()
{
using (SPSite mySite = new SPSite("http://server/sites/site"))
{
using (SPWeb myWeb = mySite.OpenWeb())
{
Stream myStream = FileUpload1.PostedFile.InputStream;
byte[] bytes = new byte[Convert.ToInt32
(FileUpload1.PostedFile.ContentLength)];
myStream.Read(bytes, 0, bytes.Length);
myStream.Close();
SPFolder myLibrary = myWeb.Folders["DocumentLibraryName"];
SPFile myFile = myLibrary.Files.Add(myLibrary.ServerRelativeUrl + "/" +
FileUpload1.FileName, bytes, false);
myLibrary.Update();
SPListItem Item = myFile.Item;
Item["ColumnName"] = "my value";
Item.Update();
}
}
}
}
}
Cheers.