How to get or read properties from a file in C#

1k Views Asked by At

I have a .cs file in a location. How do I read the file and extract only the properties from it? Is it possible to extract the properties without compiling the code? I tried with Assembly.LoadFile() and Assembly.LoadFrom() class but doesn't work!!! Here is the sample code

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Xml.Serialization;

namespace namespace1.Did
{       
    public class Class1
    {
        #region Variables

        private int _property1 = 14;
        private int _property2 = 16;

        #endregion

        #region Methods

        protected override void Initialize()
        {

        }

        protected override void OnBarUpdate()
        {
            // Have some code in this which uses System.Drawing and System.Drawing.Drawing2D dll's
        }

        #endregion

        #region Properties

        [Description("Demo1")]
        [GridCategory("Parameters")]
        public int Property1
        {
            get { return _property1; }
            set { _property1 = Math.Max(1, value); }
        }

        [Description("Demo2")]
        [GridCategory("Parameters")]
        public int Property2
        {
            get { return _property2; }
            set { _property2 = Math.Max(1, value); }
        }
        #endregion
    }
}

Actually I don't want to compile this code, since in case I am using some other dll, I need to add reference as parameter to the Csharpcodeprovider class dynamically. How do I get the properties only from this .cs file?

2

There are 2 best solutions below

0
On BEST ANSWER

You just need to read the file as plain text and parse the text using RegEx or whatever suits your needs. Since you have mentioned you cannot share the file structure(ridiculous as it sounds) you will need to work out mechanism for parsing and filtering property names by yourself.

0
On

A match something like this:

MatchCollection matches = Regex.Matches(input, @"public\s+(?<static>static\s+)?(?!class)(?<return>\w+)\s+(?<name>\w+)\s*\{", RegexOptions.Singleline);
foreach(Match match in matches)
{
    string propertyName = match.Groups["name"].Value;
    string returnType = match.Groups["return"].Value;
    bool isStatic = match.Groups["static"].Success;


}

This will work as expected in most cases, however, it will also match properties that is in a comment and properties in other classes in the same source file. You may also need to consider other modifiers than static, like virtual, abstract, override, and volatile. If you need to get the GridCategory parameters and Description parameter as well, you are really calling for trouble, also if you need to know if there is a get and set parameter.

But good luck with your quest.