Problem : Upload the file to SharePoint Document Library
Solution: Below is the code to upload the file to SharePoint Document Library.
public string SingleUpload(FileUpload uploadFile, string tblName, string columnName, string itemID, string FolderName)
{
obDoc = dt.GetList<DesignDocumentDocument>(DesignDocument);
string strReturn = string.Empty;
objWeb = spSite.OpenWeb();
if (uploadFile.PostedFile.FileName != string.Empty)
{
string fileName = Path.GetFileName(uploadFile.FileName);
string destUrl = spSite.Url + "/" + FolderName + "/" + fileName;
var lnqDesignDoc = from objDesignDoc in obDoc.ToList()
where Convert.ToString(objDesignDoc.Name) == fileName
select objDesignDoc;
if (lnqDesignDoc.Count() > 0)
{
strReturn = "0";
}
else
{
SPWeb site = new SPSite(destUrl).OpenWeb();
SPList oList = objWeb.Lists[GenerateID];//"GenerateID"
SPListItemCollection reqGenCol = oList.Items;
SPListItem reqList = reqGenCol.GetItemById(GetListItemID(reqGenCol, "UploadID", "Title"));
int upldId = Convert.ToInt32(reqList["LastID"].ToString());
reqList["LastID"] = Convert.ToString(upldId + 1);
string strUpldID = reqList["LastID"].ToString();
reqList.Update();
Stream fStream = uploadFile.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);
SPListItem slist = site.GetListItem(destUrl);
slist["itemID"] = itemID;
slist["ListName"] = tblName;
slist["ColumnName"] = columnName;
slist["DocID"] = upldId;
slist.Update();
//strFID = fileName;
//IndexCount = strFID.IndexOf('_');
//iConcat = IndexCount + 1;
//iFileCount = (strFID.Length) - (iConcat);
//strFileName = fileName.Substring(iConcat, iFileCount);
strReturn = upldId + "," + destUrl;
}
}
return strReturn;
}
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)
//{
// //return string.Empty;
//}
if (!parentFolder.Exists)
{
SPFolder currentFolder = parentSite.RootFolder;
foreach (string folder in parentFolderUrl.Split('/'))
{
currentFolder
= currentFolder.SubFolders.Add(folder);
}
}
}
return parentFolderUrl;
}
Please let us know if you have any comments regarding this solution. or if you have any better approach please share to us.
Thanks Happy SharePointers
No comments:
Post a Comment