Tuesday, March 5, 2013

Uploading files to your website and saving them on a sharepoint folder (or any folder)

I ran into a requirement where I had to implement an email attachment like feature on my web page. The user should be able to upload and retrieve a the file. We chose Sharepoint to be the host for the files.

I never worked with Sharepoint before and I felt as using the ms libraries would be complicated. Thankfully, the whole process was easier than what I expected as it is all .NET. It boils down to moving a file from one folder to another folder in a directory in the server.

Bellow is a snippet if code that would accomplish the task (I will format it later. I wish the option was in blogger)


                    string location = WebConfigurationManager.AppSettings["IssueTrackingSharepointFolderLocation"];//Shared Documents";

                    // Some browsers send file names with full path. We only care about the file name.
                    var fileName = Path.GetFileName(file.FileName);



string[] combinedPath = new string[3];
            combinedPath[0] = location;



//handle the month if iti s less than 10 and add a 0 to it
            if (date.Month < 10)
            { combinedPath[1] = date.Year.ToString() + "0" + date.Month.ToString(); }
            else
            { combinedPath[1] = date.Year.ToString() + date.Month.ToString(); }

            combinedPath[2] = entity.IssueAttachmentID.ToString() + "." + GetFileNameExtension(fileName);  //get the key with the extension

            string destinationPath = Path.Combine(combinedPath);

            string directoryPath = Path.Combine(combinedPath[0], combinedPath[1]);
            Directory.CreateDirectory(directoryPath);