Search code examples
c#wpfxsd

Generating c# file from xsd during runtime for wpf application


I'm not sure if this is possible or even a good approach but I have a WPF application that uses a c# class generated from an xsd file. This class was generated manually by using xsd.exe in the terminal. What I am looking to do is generate this class during runtime. The reason I am looking to do this is to give the option to update the xsd without having to generate a new c# file manually and the code working with updated xsd class.

PS. I do recognize this may not be the best idea considering if someone changes the xsd too much it may break the code that relies on that class (assuming this is possible in the first place).


Solution

  • While I agree with Klaus as to the advisability of doing this, it is not difficult to run xsd.exe from with your code. Something like this will do the trick:


    namepace SomeNameSpace
    {
        using System.Diagnostics;
    
        public static class SomeClassName
        {
            public static void InvokeXsd(string[] args)
            {
                var command = "xsd.exe"; // Note: need path to exe
                var startInfo = new ProcessStartInfo(command, args)
                {
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                Process.Start(startInfo)?.WaitForExit();
            }
        }
    }