1

The web part consists of following elements:

  1. a TextBox for Specifying the folder Name.
  2. asp:FileUpload to fetch the file to be uploaded.
  3. an asp:Button named Upload to upload the file. all the code needs to be written in its _click() event.

The web part has following elements


<table> <tr> <td>Enter the Name of Document Library:- </td> <td title="Enter the Name of Document Library if left blank then Default Document Liberary"> <asp:TextBox ID="txtLibraryName" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Enter the Date of Document:- </td> <td title="Enter the Date of Document if left blank then random Date"> <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Browse the File:- </td> <td title="Browse the File if not then no file will be uploaded only a folder will be created"> <asp:FileUpload ID="FileUpload" runat="server" /> </td> </tr> </table> <br /> <asp:Button ID="btnFileUpload" runat="server" Text='Upload "File" to a "Folder"' OnClick="btnFileUpload_Click" />


I have done the above program in SharePoint SSOM
`

    protected void btnFileUpload_Click(object sender, EventArgs e)
    {
        //Web initilization
        SPSite site = new SPSite("http://spappdc:33333/sites/Access");
        SPWeb web = site.OpenWeb();
        web.AllowUnsafeUpdates = true;

        //Check Date TextBox
        CheckLibrary(web);

        web.AllowUnsafeUpdates = false;
    }

`

`

    public void CheckLibrary(SPWeb web)
    {

        //Check Library TextBox
        if (txtLibraryName.Text == "")
        {
            //Get Default Document Library
            SPList documentLibrary = web.Lists.TryGetList("Documents");
            //Check Month Folder Exists
            CheckFolderExists(web, documentLibrary);
        }
        else
        {
            //Check if Library exists
            if (web.Lists.TryGetList(txtLibraryName.Text) == null)
            {
                //Create New Library
                Guid documentLibraryID = web.Lists.Add(txtLibraryName.Text, "", SPListTemplateType.DocumentLibrary);
                SPList documentLibrary = web.Lists[documentLibraryID];
                //Check Month Folder Exists
                CheckFolderExists(web, documentLibrary);
            }
            else
            {
                //Get the Library
                SPList documentLibrary = web.Lists.TryGetList(txtLibraryName.Text);
                //Check Month Folder Exists
                CheckFolderExists(web, documentLibrary);
            }
        }
    }

`

`

    //Get Date
    private string FolderName()
    {
        Random randomNo = new Random();

        int month = txtDate.Text == "" ? 1 : int.Parse(txtDate.Text.Split('/')[1]) == 12 ? 1 : int.Parse(txtDate.Text.Split('/')[1]) + 1;
        int year = txtDate.Text == "" ? 1990 : month == 1 ? int.Parse(txtDate.Text.Split('/')[2]) + 1 : int.Parse(txtDate.Text.Split('/')[2]);
        string folderName;
        txtDate.Text = "01/" + month.ToString() + "/" + year.ToString();
        string monthName = string.Empty;
        switch (month)
        {
            case 1:
                monthName = "Jan";
                break;
            case 2:
                monthName = "Feb";
                break;
            case 3:
                monthName = "Mar";
                break;
            case 4:
                monthName = "Apr";
                break;
            case 5:
                monthName = "May";
                break;
            case 6:
                monthName = "Jun";
                break;
            case 7:
                monthName = "Jul";
                break;
            case 8:
                monthName = "Aug";
                break;
            case 9:
                monthName = "Sep";
                break;
            case 10:
                monthName = "Oct";
                break;
            case 11:
                monthName = "Nov";
                break;
            case 12:
                monthName = "Dec";
                break;
        }
        return folderName = monthName + "-" + year;
    }

`

`

    //Check Month Folder Exists
    public void CheckFolderExists(SPWeb web, SPList documentLibrary)
    {
        string folderName = FolderName();
        if (web.GetFolder(documentLibrary.RootFolder.Url + "/" + folderName).Exists)
        {
            //Folder Exists Upload File
            SPFolder libraryMonthFolder = web.GetFolder(documentLibrary.RootFolder.Url + "/" + folderName);
            UploadFile(libraryMonthFolder, documentLibrary);
        }
        else
            //Create Folder And Upload
            CreateNewFolderAndUpload(documentLibrary, folderName);
        documentLibrary.Update();
    }

`

`

    //Create Folder And Upload
    public void CreateNewFolderAndUpload(SPList documentLibrary, string folderName)
    {
        SPFolder libraryMonthFolder = documentLibrary.RootFolder.SubFolders.Add(documentLibrary.RootFolder.Url + "/" + folderName);
        libraryMonthFolder.Update();
        UploadFile(libraryMonthFolder, documentLibrary);
    }

`

`

    //Upload File In Folder
    private void UploadFile(SPFolder libraryMonthFolder, SPList documentLibrary)
    {
        //upload only if file is browsed
        if (FileUpload.HasFile)
        {
            libraryMonthFolder.Files.Add(libraryMonthFolder.Url + "/" + FileUpload.FileName, FileUpload.FileBytes, true);
            libraryMonthFolder.Update();
        }
    }

`

6
  • Please provide your efforts that you have tried before. Your code or something. Commented Sep 13, 2016 at 8:53
  • Your question is not clear, Are you facing any issue? any error? What exactly is the question
    – Gaurravs
    Commented Sep 13, 2016 at 9:56
  • @DikeshGandhi updated the question Commented Sep 13, 2016 at 11:16
  • @Gaurravs the question is that I have done the program in SSOM as above mentioned and it is working fine but facing problems while doing it using CSOM Commented Sep 13, 2016 at 11:17
  • You want same code in CSOM ?
    – Gaurravs
    Commented Sep 13, 2016 at 11:20

1 Answer 1

1

Most Probable Answer in CSOM Similar to your SSOM Code could be
Select Date:<asp:TextBox ID="dateTxt" runat="server"></asp:TextBox><br /><br /> Add file:<asp:FileUpload ID="fileUpload" runat="server" /><br /><br /> <asp:Button ID="Savebtn" runat="server" Text="Save" OnClick="Savebtn_Click" /><br /><br /> <asp:Label ID="msgLbl" runat="server" Text=""></asp:Label>

`

    protected void Savebtn_Click(object sender, EventArgs e)
    {
        InputValid inputValid = new InputValid();
        if (inputValid.IsInputValid(dateTxt, fileUpload))
        {
            ClientContext clientContext = new ClientContext("http://spappdc:55555/sites/MyKM/Stocks");
            SecureString password = new SecureString();
            foreach (char a in "Zest@12345".ToCharArray())
                password.AppendChar(a);
            clientContext.Credentials = new NetworkCredential("administrator", password, "SHAREPOINT");

            Web web = clientContext.Web;
            Web rootweb = clientContext.Site.RootWeb;

            List documentLibrary = web.Lists.GetByTitle("NewLibrary");
            GetTxtboxValue getTxtValue = new GetTxtboxValue();
            getTxtValue.TxtboxValues(documentLibrary, web, clientContext, rootweb, dateTxt, fileUpload, msgLbl);
        }
        else
        {
            msgLbl.Text = "Please enter valid input!!";
            msgLbl.ForeColor = System.Drawing.Color.Red;
        }

    }

`

`

class InputValid
{
    public bool IsInputValid(TextBox dateTxt, FileUpload fileUpload)
    {
        if (string.IsNullOrEmpty(dateTxt.Text))
            return false;
        if (string.IsNullOrEmpty(fileUpload.FileName))
            return false;

        return true;
    }
}

class GetTxtboxValue
{
    public void TxtboxValues(List documentLibrary, Web web, ClientContext clientContext, Web rootWeb, TextBox dateTxt, FileUpload fileUpload, Label msgLbl)
    {

        //Get the value from textbox 
        string txtValue = dateTxt.Text;
        string date = txtValue.Split('/')[0];
        string month = txtValue.Split('/')[1];
        string year = txtValue.Split('/')[2];
        string monthName = string.Empty;
        switch (month)
        {
            case "01":
                monthName = "January";
                break;
            case "02":
                monthName = "February";
                break;
            case "03":
                monthName = "March";
                break;
            case "04":
                monthName = "April";
                break;
            case "05":
                monthName = "May";
                break;
            case "06":
                monthName = "June";
                break;
            case "07":
                monthName = "July";
                break;
            case "08":
                monthName = "August";
                break;
            case "09":
                monthName = "September";
                break;
            case "10":
                monthName = "October";
                break;
            case "11":
                monthName = "November";
                break;
            case "12":
                monthName = "December";
                break;
        }

        clientContext.Load(documentLibrary.RootFolder.Folders);
        clientContext.ExecuteQuery();
        Folder folder = documentLibrary.RootFolder.Folders[0];
        bool isFolderPresent = false;
        foreach (Folder fld in documentLibrary.RootFolder.Folders)
            if (fld.Name == monthName + "-" + year)
            {
                folder = fld;
                isFolderPresent = true;
            }
        FolderCreationAndFileUpload fldCreate = new FolderCreationAndFileUpload();
        if (isFolderPresent == false)
        {
            //create newFile and assning to folder

            fldCreate.FolderCreation(clientContext, documentLibrary, monthName, year, fileUpload);
            msgLbl.Text = "Folder Created And File Uploaded";
        }
        else
        {
            //upload file in existing one

            fldCreate.UploadFile(clientContext, folder, fileUpload);
            msgLbl.Text = "File Uploaded in Existing One ";
        }
    }
}

class FolderCreationAndFileUpload
{
    public void FolderCreation(ClientContext clientContext, List documentLibrary, string monthName, string year, FileUpload fileUpload)
    {
        documentLibrary.EnableFolderCreation = true;
        documentLibrary.Update();
        clientContext.ExecuteQuery();
        clientContext.Load(documentLibrary.RootFolder); clientContext.ExecuteQuery();
        Folder docLibraryFolder = documentLibrary.RootFolder.Folders.Add(documentLibrary.RootFolder.ServerRelativeUrl + "/" + monthName + "-" + year);
        clientContext.Load(docLibraryFolder); clientContext.ExecuteQuery();
        docLibraryFolder.Update();

        UploadFile(clientContext, docLibraryFolder, fileUpload);
        documentLibrary.Update();

    }
    public void UploadFile(ClientContext clientContext, Folder docLibraryFolder, FileUpload fileUpload)
    {
        FileCreationInformation fileInfo = new FileCreationInformation
        {
            Content = fileUpload.FileBytes,
            Overwrite = true,
            Url = docLibraryFolder.ServerRelativeUrl + "/" + fileUpload.FileName,

        };
        clientContext.Load(docLibraryFolder.Files); clientContext.ExecuteQuery();
        docLibraryFolder.Files.Add(fileInfo);
        clientContext.ExecuteQuery();
        docLibraryFolder.Update();
    }
}

`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.