How to read an XML file from a Web Part in SharePoint

I have an XML file containing some data that I should read from the Web Part code in SharePoint 2010 (in my case I have a file containing a default configuration stored as XML).

One possible way to read such file is to embed it into the Web Part assembly then use the method GetManifestResourceStream to read it from code.

Suppose to have a SharePoint project named “NetglooWebParts” containing a Web Part named “CustomWebPart”, you should have a project structure like this (from Visual Studio):

NetglooWebParts/
  + Properties/
  + References/
  ...
  + CustomWebPart/  
  |  - CustomWebPart.webpart
  |  - CustomWebPart.cs
  |  - DefaultConfig.xml
  |  - Elements.xml
  ...

where DefaultConfig.xml is the file you want to read.

Now, you must select the file from Visual Studio, go on Properties (e.g. right-clicking on the file), choose Embedded Resource as Build Action (the first property in my case).

After that you can use the following code (C# language) to read such file:

string defaultConfig = "";

Stream stream =
  GetType().Assembly.GetManifestResourceStream(
    "NetglooWebParts." +
    "CustomWebPart." +
    "DefaultConfig.xml");

if (stream != null)
{
  using (var rdr = new StreamReader(stream))
  {
      defaultConfig = rdr.ReadToEnd();
  }
}

If you get a null stream, typical errors are to forget to embed the file (see here), or to write a wrong path (e.g. without the namespace) as argument in the method GetManifestResourceStream (more here).

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2016 Netgloo