Monday, April 19, 2010

Uploading file to Sharepoint document library

Uploading files to a SharePoint document library through the web UI is a fairly simple process, but did you know it’s also possible to programmatically upload a file (or string) to a document library?

I am writing a generic function which upload a file into document library. It needs following parameters:-
string textToOutput: This is string data which need to write in file
string strDocLib: This is documnet library path like- "/DocLib/Forms/AllItems.aspx"
string strFileName: "Report.xls" or "Report.txt"
string strSiteUrl: "http://localhost:2100"

Once you have all these parameters you can use following generic function which will upload file into document library on publishing portal or Collaboration site:-


protected void UpdateFileInDocLib(string textToOutput, string strDocLib, string strFileName, string strSiteUrl)
{
try
{
string uploadPath = string.Empty;

string[] strDocLibName = strDocLib.Split('/');
if (String.IsNullOrEmpty(strFileName))
{
string strDate = DateTime.Now.ToString();
strDate = strDate.Replace('/', '_');
strDate = strDate.Replace(':', '_');
uploadPath = strSiteUrl + "/" + strDocLibName[1] + "/" + strDate + ".txt";
}
else
{
uploadPath = strSiteUrl + "/" + strDocLibName[1] + "/" + strFileName;
}
using (SPSite baseSite = new SPSite(strSiteUrl))
{
using (SPWeb baseWeb = baseSite.OpenWeb())
{
baseWeb.AllowUnsafeUpdates = true;
SPFile document = null;
// Convert string to bytes
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] contents = encoder.GetBytes(textToOutput.ToString());
// Insert other metadata while uploading file
Hashtable htParameters = new Hashtable();
htParameters[_listColumn3] = dtReportData.Rows.Count;

if (baseWeb.GetFile(uploadPath).Exists)
baseWeb.GetFile(uploadPath).Delete();
// upload file
document = baseWeb.Files.Add(uploadPath, contents, htParameters, true);
document.CheckIn("", SPCheckinType.MajorCheckIn);
document.Publish("");
document.Approve("Approved by program");
baseWeb.AllowUnsafeUpdates = false;

Console.WriteLine("File uploaded successfully\n");
}
}
}
catch (SPException ex)
{
Console.WriteLine("File uploaded successfully\n");
}
catch
{
}
}


For input, If you have file rather than string then you can use following code to get bytes:-

=====================================================
string localFilename = "";// ex. c:\temp\myFileToUpload.doc FileStream myStream = new FileStream(localFilename, FileMode.Open, FileAccess.Read);
BinaryReader myReader = new BinaryReader(myStream);
byte[] contents = reader.ReadBytes((int)myStream.Length);
======================================================

And rest process would be same..


Thanks!
Avinash

No comments: