private static void CreateFolder(FileUploadParam fileUploadParam)
 {
     try
     {
         string folderName = highestFolderName.Substring(0, fileUploadParam.FolderPrefix.Length) + (++maxFolderIndex).ToString();
         fileUploadParam.TargetList.RootFolder.SubFolders.Add(folderName);
         highestFolderName = folderName;
         siteUrl           = fileUploadParam.TargetList.ParentWeb.Url + "/" + fileUploadParam.TargetList.Title + "/" + folderName + "/" + fileUploadParam.CurrentFileName;
         AddFilesToSP(siteUrl, fileUploadParam.TargetList, highestFolderName, fileUploadParam.FileContent, fileUploadParam.CreatedBy, fileUploadParam.ModifiedBy, fileUploadParam.CreatedDate, fileUploadParam.ModifiedDate);
     }
     catch (Exception)
     {
         throw new Exception("Problem while creating folder in " + fileUploadParam.TargetList);
     }
 }
        public static SPFile UploadFilesInSharePoint(FileUploadParam fileUploadParam)
        {
            int fileCount = fileUploadParam.HighestFolderFileCount;

            siteUrl = fileUploadParam.TargetList.ParentWeb.Url + "/" + fileUploadParam.TargetList.Title + "/" + highestFolderName + "/" + fileUploadParam.CurrentFileName;
            try
            {
                if (fileCount >= fileUploadParam.AllowedFileLimit)
                {
                    CreateFolder(fileUploadParam);
                }
                else
                {
                    AddFilesToSP(fileUploadParam.SiteUrl, fileUploadParam.TargetList, highestFolderName, fileUploadParam.FileContent, fileUploadParam.CreatedBy, fileUploadParam.ModifiedBy, fileUploadParam.CreatedDate, fileUploadParam.ModifiedDate);
                }
            }
            catch (Exception)
            {
                throw new Exception("Unable to Archive Files. Please try again.");
            }
            return(null);
        }
        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (tbxUserName.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxUserName, "User Name is required");
                tbxUserName.Focus();
            }
            else if (tbxPassword.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxPassword, "Password is required");
                tbxPassword.Focus();
            }
            else if (tbxDomain.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxDomain, "Domain is required");
                tbxDomain.Focus();
            }
            else if (tbxSharePointURL.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxSharePointURL, "SharePoint Site is required");
                tbxSharePointURL.Focus();
            }
            else if (drpdnlFormLibrary.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(drpdnlFormLibrary, "Formlibrary is required");
                drpdnlFormLibrary.Focus();
            }
            else
            {
                int highestFolderFileCount = 0;
                //int fileCount = 1;
                string        siteUrl         = String.Empty;
                byte[]        byteArr         = null;
                StreamReader  streamReader    = null;
                FileInfo[]    fileCollections = null;
                DirectoryInfo dirInfo         = null;
                StringBuilder fileName        = new StringBuilder();
                FileStream    fileStream      = null;

                try
                {
                    WindowsImpersonationContext wic = Utility.CreateIdentity(tbxUserName.Text.Trim(), tbxDomain.Text.Trim(), tbxPassword.Text.Trim()).Impersonate();

                    SPSite site = null;

                    //Check whether user enters full url of the site including "http"
                    if (tbxSharePointURL.Text.StartsWith("http"))
                    {
                        site = new SPSite(tbxSharePointURL.Text.Trim());
                    }
                    else
                    {
                        site = new SPSite("http://" + tbxSharePointURL.Text.Trim());
                    }
                    //MessageBox.Show(site.Url + "/" + drpdnlFormLibrary.Text.Trim());
                    SPWeb            web       = site.OpenWeb();
                    string           weburl    = web.Url;
                    SPFileCollection filesInSP = web.Files;

                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates  = true;

                    SPFile sharePointFile = null;
                    dirInfo         = new DirectoryInfo(tbxTargetFolder.Text.Trim());
                    fileCollections = dirInfo.GetFiles();

                    XmlDocument     xmlInputData = new XmlDocument();
                    XmlDataDocument xmlUserMap   = new XmlDataDocument();

                    LoadUserMapping(ref xmlUserMap);

                    //DataTable dtInputData = LoadInput2table(xmlInputData);
                    int      maxNumber     = 0;
                    SPFolder highestFolder = null;
                    string   tempSiteUrl   = String.Empty;
                    if (cbxFolderStructure.Checked)
                    {
                        highestFolder          = FileSplitUtility.GetHighestFolder(web, drpdnlFormLibrary.Text.Trim(), tbxArchiveFolderPrefix.Text, ref maxNumber);
                        highestFolderFileCount = highestFolder.Files.Count;
                        tempSiteUrl            = weburl + "/" + drpdnlFormLibrary.SelectedItem.ToString() + "/" + highestFolder.Name;
                    }
                    else
                    {
                        tempSiteUrl = weburl + "/" + drpdnlFormLibrary.SelectedItem.ToString();
                    }

                    FileUploadParam fileUploadParam = null;
                    string          currentUser     = tbxDomain.Text + "/" + tbxUserName.Text;

                    foreach (FileInfo file in fileCollections)
                    {
                        fileName.Append(file.FullName.Substring(file.DirectoryName.Length));

                        if (fileName.Length > 128)
                        {
                            fileName.Replace(fileName.ToString(), fileName.ToString().Substring(0, 124));
                            fileName.Append(file.Extension);
                        }
                        fileStream = file.Open(FileMode.Open, FileAccess.Read);
                        siteUrl    = tempSiteUrl + "/" + fileName.ToString().Substring(fileName.ToString().LastIndexOf(@"\") + 1);


                        streamReader = new StreamReader(fileStream);

                        byteArr = System.Text.Encoding.ASCII.GetBytes(streamReader.ReadToEnd());

                        string fileNameWithoutExtn = fileName.ToString().Substring(1, fileName.Length - 5);

                        try
                        {
                            //DateTime dtCreatedDate = Convert.ToDateTime("10-10-2006");//drCurrRecord["CreatedDate"]);
                            //DateTime dtModifiedDate = Convert.ToDateTime("10-10-2006");//drCurrRecord["LastModifiedDate"]);

                            //Check whether user needs folder structure to upload the files,
                            //If yes, assign values to file upload parameters
                            if (cbxFolderStructure.Checked)
                            {
                                //Assigning values to the parameters for uploading files.
                                fileUploadParam = new FileUploadParam();
                                //fileUploadParam.CreatedBy = strCreatedWinUser;
                                //fileUploadParam.ModifiedBy =strModifiedWinUser;
                                fileUploadParam.FileContent            = byteArr;
                                fileUploadParam.CurrentFileName        = fileName.ToString();
                                fileUploadParam.HighestFolderName      = highestFolder.Name;
                                fileUploadParam.HighestFolderFileCount = highestFolderFileCount;
                                fileUploadParam.FolderPrefix           = tbxArchiveFolderPrefix.Text.Trim();
                                fileUploadParam.SiteUrl    = siteUrl;
                                fileUploadParam.TargetList = web.Lists[drpdnlFormLibrary.Text.Trim()];
                                //fileUploadParam.CreatedDate =dtCreatedDate;
                                //fileUploadParam.ModifiedDate = dtModifiedDate;
                                fileUploadParam.AllowedFileLimit = int.Parse(tbxMaxFileLimit.Text);

                                sharePointFile = FileSplitUtility.UploadFilesInSharePoint(fileUploadParam);

                                if (highestFolderFileCount >= int.Parse(tbxMaxFileLimit.Text.Trim()))
                                {
                                    highestFolderFileCount = 0;
                                }
                                ++highestFolderFileCount;
                            }
                            else
                            {
                                try
                                {
                                    //SPUser creator = web.Users[strCreatedWinUser];
                                    //SPUser modifier = web.Users[strModifiedWinUser];

                                    //if (creator.LoginName != "" && modifier.LoginName != "")
                                    //{
                                    //    sharePointFile = filesInSP.Add(siteUrl, byteArr, creator, modifier, dtCreatedDate, dtModifiedDate);
                                    //}
                                    //else
                                    //{
                                    sharePointFile = filesInSP.Add(siteUrl, byteArr, true);
                                    //}
                                }
                                catch (Exception exception)
                                {
                                    LogInfo("ERROR while convertin winuser to SPUser for file:" + fileName.ToString() + "  Error:" + exception.Message);
                                    sharePointFile = filesInSP.Add(siteUrl, byteArr, true);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            if (highestFolderFileCount >= int.Parse(tbxMaxFileLimit.Text.Trim()))
                            {
                                highestFolderFileCount = 0;
                            }
                            ++highestFolderFileCount;
                        }
                        //ends here

                        fileStream.Flush();
                        fileName.Remove(0, fileName.Length);
                    }
                    wic.Undo();
                    MessageBox.Show("Uploaded Successfully", "Upload");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in  uploading the file " + fileName + Environment.NewLine +
                                    "Cannot proceed further." + Environment.NewLine +
                                    "See log file for more details in root folder", "Upload Error");
                    StreamWriter logWriter = new StreamWriter(dirInfo.Root + "/Log.txt", false);
                    logWriter.Write("Error Message: " + ex.Message + System.Environment.NewLine + "Source of Error: " + fileName);
                    logWriter.Flush();
                    return;
                }
                finally
                {
                    streamReader.Close();
                    fileStream.Close();
                }
            }
        }