Search code examples
c#visual-studioopcopc-da

System.AccessViolationException Visual Studio


When i compile there is no error but i have this exception (System.AccessViolationException ) even though this is a pretty simple code i am new to c# and can't find the problem the url is correct but it does connect to my server and i'm using the proper packages but i doesnt scan the tags the exception is in line : OpcDaBrowseElement[] elements = browser.GetElements(itemId);

The exception : System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Da;
using TitaniumAS.Opc.Client.Da.Browsing;
using System.Threading;

namespace OPCDA
{
    class Program
    {
        static void Main(string[] args)
        {

            TitaniumAS.Opc.Client.Bootstrap.Initialize();

            Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1");

            using (var server = new OpcDaServer(url))
            {
                server.Connect();
                var browser = new OpcDaBrowserAuto(server);
                BrowseChildren(browser);
            }

            
            void BrowseChildren(IOpcDaBrowser browser, string itemId = null, int indent = 0)
            {
                OpcDaBrowseElement[] elements = browser.GetElements(itemId);

                foreach (OpcDaBrowseElement element in elements)
                {
                    Console.Write(new string(' ', indent));
                    Console.WriteLine(element);

                    if (!element.HasChildren)
                        continue;

                    BrowseChildren(browser, element.ItemId, indent + 2);
                    

                }
            }
        }
    }
}

Solution

  • The problem is solved, all i did was change the build parameters to 32bit instead if 64 and it worked Project\Build\CPU x86