Saturday, 17 December 2011

Upload Document Library using Server Object Model

This is the  code

using (SPSite siteCollection = new SPSite("http://igrid103:1990"))
            {
                using (SPWeb spWeb = siteCollection.OpenWeb())
                {
                    SPList spList = spWeb.Lists.TryGetList("Shared Documents");

                    string fileName = "new resume.doc";
                    FileStream fileStream = null;
                    Byte[] fileContent = null;

                    try
                    {
                        string docPath =@"D:\anand raj\"; //physical location of the file
                        fileStream = File.OpenRead(docPath + fileName);
                        fileContent = new byte[Convert.ToInt32(fileStream.Length)];
                        fileStream.Read(fileContent, 0, Convert.ToInt32(fileStream.Length));

                        spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + fileName, fileContent, true);
                        spList.Update();
                    }
                    catch (Exception ex)
                    {

                    }
                    finally
                    {
                        if (fileStream != null)
                        {
                            fileStream.Close();
                        }
                    }
                }
            }

No comments:

Post a Comment