SharePoint C#上传文件到文档库

                 try
                {
                    String fileToUpload =  " C:\test.txt ";
                    String sharePointSite =  " http://localhost:80/ ";
                    String documentLibraryName =  " test ";
                    SPSecurity.RunWithElevatedPrivileges( delegate()
                    {
                     using (SPSite oSite =  new SPSite(sharePointSite))
                    {
                         using (SPWeb oWeb = oSite.RootWeb)
                        {
                            oWeb.AllowUnsafeUpdates =  true;
                             if (!System.IO.File.Exists(fileToUpload))
                                 throw  new Exception( " File not found. ");

                            SPDocumentLibrary myLibrary = oWeb.Lists[documentLibraryName]  as SPDocumentLibrary;

                             //  Prepare to upload
                            Boolean replaceExistingFiles =  true;
                            String fileName = System.IO.Path.GetFileName(fileToUpload);
                            FileStream fileStream = File.OpenRead(fileToUpload);

                             //  Upload document
                            SPFile spfile = myLibrary.RootFolder.Files.Add(oWeb.Url.ToString() +  " / " + myLibrary.Title.ToString() +  " / " + fileNameWithoutExt + fileExtName, fileStream, replaceExistingFiles);

                             //  Commit 
                            spfile.Update();
                            myLibrary.Update();
                            oWeb.Update();
                            oWeb.AllowUnsafeUpdates =  false;
                        }
                    }
                    });

                }
                 catch (Exception SPError)
                {
                    Response.Write(SPError.Message);
                }

你可能感兴趣的:(SharePoint)