سؤال

I have a javascript code like this:

  o = new ActiveXObject("ASDFsome.Application");
  utilites = WScript.CreateObject("ASDF.Utilites.UTF.Converter")
  utilites.Convert(outFile, xmlProp.xml)

Now I want to rewrite it in C# code. How should I use ActiveXObject in Net?

هل كانت مفيدة؟

المحلول

This is in no small part why the dynamic keyword was added to C# version 4:

dynamic utilites = Activator.CreateInstance(Type.GetTypeFromProgID("ASDF.Utilites.UTF.Converter"));
utilites.Convert(outFile, xmlProp.xml);

If you're stuck on an earlier version then using a VB.NET class library is the best approach. It directly supports the CreateObject() function as used in your scripting code.

Last but not least, unlike the scripting language you've been using, both C# and VB.NET support early binding. That starts by adding a reference to the type library, Project + Add Reference and use either the COM tab or the Browse tab to pick the .tlb or .dll file that contains the type library. You might not have one if the component was designed to be only ever used from late binding scripting languages. We can't otherwise help you find the proper type library, the vendor or author would know.

Really last but not least, this smells like a utility that knows how to read a utf-8 encoded XML file. That's already really well supported in .NET with the System.Xml namespace.

نصائح أخرى

One possibility is to use Reflection:

var utilitiesType = Type.GetTypeFromProgID("ASDF.Utilites.UTF.Converter");
var instance = Activator.CreateInstance(utilitiesType);
utilitiesType.InvokeMember(
    "Convert", 
    BindingFlags.InvokeMethod | BindingFlags.Public, 
    null, 
    instance, 
    new[] { "outputFile", "xmlProp.xml" }
);

Another possibility is to generate a strongly typed proxy for the COM object. Right click on your project, Add Reference -> COM tab -> Select the COM object in the list or load it from its DLL. Visual Studio will then generate a strongly typed wrapped assembly for this COM object and automatically add it as reference. Next you could work with the COM object directly and by keeping its strong typing.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top