Most of the SharePoint will love to use the tools inside the SharePoint site to upload their .dwp or .webparts files into the webpart gallery but sometimes, we do encounter chances that we will need to do the upload from inside the code (the programmatic way). It is not a very hard task though provided SharePoint does have a very complete and easy-to-use Object Model.
As usual, we will need to open the site collection and the web of the SharePoint site like the following two lines of codes (in ASP.NET C#). Then, we'll need to set both the site collection and site to accept unsafe webparts to be updated into its web part gallery.
SPSite siteCol = new SPSite("http://hostservername"); SPWeb site = siteCol.RootWeb; site.AllowUnsafeUpdates = true; siteCol.AllowUnsafeUpdates = true;
Then it is the time to get the file(.dwp or .webpart) we wished to be streamed and then saved into the gallery. We can achieve this by passing a local or dynamically created file into the FileInfo class. After that, we'll need to turn the file into a file stream with the mode set to open and the access to read only.
FileInfo file = new FileInfo("C:\\Users\\Somebody\\Desktop\\projectname\\mywebpart.dwp"); FileStream stream = file.Open(FileMode.Open, FileAccess.Read)
After that, we'll need to open the list in which the web part gallery is located (almost everything in SharePoint is a kind of custom list). From the list we'll open its root folder in which the real file is being stored. From there, we'll use a SPFile instance to stream the file(created earlier) into the gallery and update it.
SPList list = site.Lists["Web Part Gallery"]; SPFolder root = list.RootFolder; SPFile dwpFile = root.Files.Add("mywebpart.dwp", stream); dwpFile.Update();
So that's the ways to getting web parts uploaded to the gallery in a more tedious way.
Comments (1)
Sep 10, 2009
Anonymous says:
Thanks--this was a big help. I changed it around a little so that the site is o...Thanks--this was a big help.
I changed it around a little so that the site is opened with "using" and after updating the file, I put a stream.Dispose() line.