I debugged this code and it never throws me an exception, however after ALL code is executed I got this message
Trying to use an SPWeb object that has been closed or disposed and is no longer valid.
protected void Button1_Click(object sender, EventArgs e)
{
CreateDestinationDocumentLibrary(TxtDocumentLibraryName.Text, TxtDestinationSiteUrl.Text);
CopyFilesFromRoot(TxtDocumentLibraryName.Text, TxtDestinationSiteUrl.Text);
}
private void CreateDestinationDocumentLibrary(string documentLibraryname, string destinationSiteUrl)
{
using (SPSite oSPSite = SPContext.Current.Site)
{
using (SPWeb oSPWeb = oSPSite.OpenWeb(destinationSiteUrl))
{
SPList newDocLibrary = oSPWeb.Lists.TryGetList(documentLibraryname);
if (newDocLibrary == null)
{
oSPWeb.Lists.Add(documentLibraryname, documentLibraryname, SPListTemplateType.DocumentLibrary);
}
}
}
}
public void CopyFilesFromRoot(string documentLibraryname, string destinationSiteUrl)
{
using (SPSite oSPSite = SPContext.Current.Site)
{
using (SPWeb oSPWeb = oSPSite.RootWeb)
{
SPFolder oFolder = oSPWeb.GetFolder(documentLibraryname);
SPFileCollection collFile = oFolder.Files;
//Copying files from the Root folder.
CopyFiles(destinationSiteUrl, documentLibraryname, collFile);
// Get the sub folder collection
SPFolderCollection collFolder = oFolder.SubFolders;
EnumerateFolders(destinationSiteUrl, documentLibraryname, collFolder);
}
}
}
public void CopyFiles(string destinationSiteUrl, string documentlibraryname, SPFileCollection collFile)
{
//SPFileCollection collFile = oFolder.Files;
foreach (SPFile oFile in collFile)
{
oFile.CopyTo(destinationSiteUrl + "/" + documentlibraryname, true);
}
}
private void EnumerateFolders(string destinationSiteUrl, string documentlibraryname, SPFolderCollection copyFolders)
{
foreach (SPFolder subFolder in copyFolders)
{
if (subFolder.Name != "Forms")
{
SPFileCollection subFiles = subFolder.Files;
CopyFiles(destinationSiteUrl, documentlibraryname, subFiles);
}
SPFolderCollection subFolders = subFolder.SubFolders;
EnumerateFolders(destinationSiteUrl, documentlibraryname, subFolders);
}
}