This post going to describe that how to create a Folder(Main Folder) within a Document Library and create a Sub Folder within Main Folder and upload files to Sub Folder.
private void UploadContractDocuments(string paraMainFolderName, string paraSubFolderName,
string paraContractNumber, DateTime paraStartDate, DateTime paraEndDate)
{
try
{
string mainFolderName = paraMainFolderName;
string subFolderName = paraSubFolderName;
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
site.AllowUnsafeUpdates = false;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//Check whether file upload control contains a file
if (ContractFileUpload.HasFile)
{
SPDocumentLibrary documentLibrary = web.Lists["ContractDocuments"] as SPDocumentLibrary;
string FolderPath = documentLibrary.RootFolder.Url + "/" + mainFolderName;//Main folder path
string SubFolderPath = documentLibrary.RootFolder.Url + "/" + mainFolderName + "/" + subFolderName;//Sub folder path
//Check whether main folder already exist
if (!web.GetFolder(FolderPath).Exists)
{
//Create main folder if not exist
SPListItem newFolder = documentLibrary.Items.Add("", SPFileSystemObjectType.Folder, mainFolderName);
newFolder.Update();
//Create sub folder inside main folder
string subFolderUrl = web.Url + "/" + newFolder.Url;
SPListItem subFolder1 = documentLibrary.Items.Add(subFolderUrl, SPFileSystemObjectType.Folder, subFolderName.ToString());
subFolder1.Update();
}
else
{
//Check for subfolder if main folder is already exist
if (!web.GetFolder(SubFolderPath).Exists)
{
//Create sub folder if not exist
string subFolderUrl = FolderPath;
SPListItem subFolder1 = documentLibrary.Items.Add(subFolderUrl, SPFileSystemObjectType.Folder, subFolderName.ToString());
subFolder1.Update();
}
}
Stream fStream = RequestModuleFileUpload.PostedFile.InputStream;
byte[] _byteArray = new byte[fStream.Length];
fStream.Read(_byteArray, 0, (int)fStream.Length);
fStream.Close();
string fileName = RequestModuleFileUpload.PostedFile.FileName;
string _fileUrl = documentLibrary.RootFolder.Url + "/" + mainFolderName + "/" + subFolderName + "/" + Path.GetFileNameWithoutExtension(fileName) + Path.GetExtension(fileName);
bool IsOverwriteFile = true;
//Create meta data
var docMetadata = new Hashtable {
{ "ContractNumber", paraContractNumber },
{ "StartDate", paraStartDate},
{ "EndDate", paraEndDate }
};
SPFile file = documentLibrary.RootFolder.Files.Add(_fileUrl, _byteArray, docMetadata, IsOverwriteFile);
SPListItem item = file.Item;
file.Update();
documentLibrary.Update();
}
}
}
}
catch (Exception)
{
throw;
}
}
No comments:
Post a Comment