You will need to use the appropriate Resource. In your case, it's in core.resx, resource key "webpartgalleryList". Note that the Web Part Gallery is always at the root of the site collection, so for maximum portability you should access it using web.Site.RootWeb, not web. Also, SPListCollection[string listName] will already throw an exception if the list is not found, so no need to rethrow your own.
So, modify your code to:
string file = "MyWebPart.webpart";
string webPartGalleryListName = SPUtility.GetLocalizedString("webpartgalleryList", "core", (uint)web.Language);
var webPartList = web.Site.RootWeb.Lists[webPartGalleryListName];
Alternatively, a better, more performant option, would be to get the list using its URL, which for this library is invariant :
string siteUrl = web.Site.ServerRelativeUrl;
if (!siteUrl.EndsWith("/"))
{
siteUrl += "/";
}
var webPartList = web.Lists.GetList(siteUrl + "_catalogs/wp");
...
Lastly, a few notes on your loop in the second part of your code example.
- You gain nothing with .Cast().ToList(), there is already an enumerator on SPListItemCollection. These two calls will cause the entire list to enumerate twice initially.
- Instead of getting a new list to work with to be able to delete without getting the error "Collection was modified", you could use a for(;;) construct, which does allow you to modify the subject of the loop. In this case it is important to set aside SPList.Items in a SPListItemCollection object before entering the loop, otherwise using SPList.Items[index] will re-fetch the entire collection on each iteration.
- You don't need to call SPList.Update() when deleting items. Regardless, you could have called it only once after the loop.
- You should consider using a CAML query to specifically find matching names instead of looping through everything and selecting matching items post-query.
- Also consider not fetching all fields for each item, as you just want to delete them. I'm not 100% sure here but I think only getting the ID and Name fields would be sufficient for your purpose. See point #2 here