Wednesday 28 March 2012

Upload Files into sharepoint library using FileUpload control

string documentlibraryname = ConfigurationManager.AppSettings["DocumentLibraryName"];
string folderpath = ConfigurationManager.AppSettings["TempFolderLocation"];

try
{
HttpFileCollection hfc = Request.Files;

for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
//folderpath +
//Get proper file name
string strFileName = hpf.FileName;
strFileName = Path.GetFileName(strFileName);

string TempFileName = folderpath + strFileName;
hpf.SaveAs(TempFileName);
String fileToUpload = TempFileName;
String sharePointSite = SPContext.Current.Web.Url;
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
string[] folders = folderName.Split(';');
String url = oWeb.Lists[documentlibraryname].RootFolder.ServerRelativeUrl.ToString();
foreach (string subFolder in folders)
{
url += "/" + subFolder.Trim();
}
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
SPFile spfile = oWeb.GetFolder(url).Files.Add(fileName, fileStream, replaceExistingFiles);
spfile.Item["Name"] = fileName;
spfile.Item["Created By"] = SPContext.Current.Web.CurrentUser;
spfile.Item["Modified By"] = SPContext.Current.Web.CurrentUser;
spfile.Item.Update();
fileStream.Flush();
fileStream.Close();
fileStream.Dispose();
oWeb.AllowUnsafeUpdates = false;
}
}
}
}
}

catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
HttpFileCollection hfc1 = Request.Files;
if(hfc1.Count==0)
lblMessage.Text = "Please select at least one file to upload";

1 comment:

  1. A bunch of code, but one is not sure what to do with it?????

    ReplyDelete