Can't add a static port mapping in my c# application

梦想的初衷 提交于 2019-12-01 16:28:36

You need to set mappings to a new instance:

For example:

var mappings = new List<Mapping>();

Then you can call:

mappings.Add(8000, "TCP", 8000, "192.168.1.100", true, "Local Web Server");

From your edit:

upnpnat.StaticPortMappingCollection; // this is your problem.  

The collection is coming back as null. Therefore you cannot add to the collection.

You may have to do:

NATUPNPLib.IStaticPortMappingCollection mappings = new StaticPortMappingCollection();

From Codesleuth's comment:

I believe the answer is that his router isn't configured as a UPnP gateway, or that he has no permissions. The StaticPortMappingCollection is null if either of those cases are true. I suggest you edit this into your answer as you've got the right reason for the error anyway. Checking for null first is the only way to deal with the error

Without more code we would be able to help, but if the exception is on the line you provided, that means that mappings is null and not set.

Check the code before that line to see if you're actually creating and setting the mappings variable.

According to your comment, the object returned by upnpnat.StaticPortMappingCollection is what is null. Check the documentation to make sure you're initializing it correctly.

Just based on your error message which just all we have;

var mappings = new List<Mapping>();
mappings.Add(8000, "TCP", 8000, "192.168.1.100", true, "Local Web Server");

After your edit, maybe using like;

NATUPNPLib.IStaticPortMappingCollection mappings = new StaticPortMappingCollection();

Looks like you forget to use ()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!