Introduction
We needed to use an alternative to the Visual Basic GetObject
function in C#. Marshal.BindToMoniker
would do. But we can not, as in Visual Basic, directly reference the object returned and its methods or properties. We use the obj.GetType().InvokeMember
method for this purpose. In this example, we will set the IIS Virtual Directory Basic Authentication using the IIsWebService
COM interface.
- File -> New -> New Project
Create a new CSGetObject
Visual C# Windows application.
-
From the main menu, click View -> Tool box.
-
Drag a Button
into the form.
-
Double click the Button1
.
-
Replace the button1_Click
method with the following code:
private void button1_Click(object sender, System.EventArgs e)
{
try
{
Object obj = Marshal.BindToMoniker("IIS://LocalHost/W3svc/1/Root");
bool v = (bool) obj.GetType().InvokeMember("AuthBasic",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.GetProperty, null, obj, null);
MessageBox.Show(v.ToString ());
obj.GetType().InvokeMember("AuthBasic",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, obj, new Object[] {!v});
obj.GetType().InvokeMember("SetInfo",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod,
null, obj, null);
}
catch (Exception er)
{
MessageBox.Show(er.Message, "Error!!");
}
}
Add:
using System.Runtime.InteropServices;
using System.Reflection;
to the imports. Build the solution (F7), and run the application (F5).
Points of Interest
That's it!
History
Just posted.