Thursday, December 3, 2009

Custom Web Part to Display file (.html, .txt, .xml) contents

The following code builds a web part,  that can disply the contents on any file(.txt, .xml, .html are tested so far) on the page.

 

After adding the web part to the page, edit the web part properties and in the miscellanious section specifiy the file location (e.g. C:\Foler\FileName.txt).

 

using System;

using System.IO;

using System.Runtime.InteropServices;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

 

namespace CLIENTName.WebPartName

{

    [Guid("1cba1a69-02b8-482c-b634-73cad1a46aa6")]

    public class WebPartName: System.Web.UI.WebControls.WebParts.WebPart

    {

 

        string filePath = @"C:\MyHTML.htm";

        [WebBrowsable(true), WebDisplayName("File Path"), WebDescription("Enter the file path"), Personalizable(PersonalizationScope.Shared)]

        public String FilePath { get { return filePath; } set { filePath = value; } }

    

        public WebPartName ()

        {

        }

 

        protected override void CreateChildControls()

        {

            base.CreateChildControls();

            Label label = new Label();

            //label.Text = "Hello World";

            label.Text = GetFileContents(this.FilePath);         

            this.Controls.Add(label);

        }

        /// <summary>

        ///

        /// </summary>

        /// <param name="FullPath"></param>

        /// <returns></returns>

        public string GetFileContents(string FullPath)

        {

 

            string strContents = null;

            StreamReader objReader = default(StreamReader);

            try

            {

                objReader = new StreamReader(FullPath);

                strContents = objReader.ReadToEnd();

                objReader.Close();

                return strContents;

            }

            catch (Exception Ex)

            {

                throw Ex;

            }

        }

 

    }

}

 

0 comments: