在代码中设置开关

时间:2017-11-28 09:33:25

标签: c# .net

我正在尝试在我的控制台应用程序中嵌入以下开关设置,但我不需要app.config。还有另一种方法可以在应用程序中设置此开关吗?

我遇到 <table id="table" cellpadding="0" cellspacing="0" border="0" align="center"> <tr height="35" id="CompName" style="display:none"> <td width="150">Select Company:</td> <td width="200"> <select class="textbox" name="cboCompName" style="width:178px" id ="cboCompName"> <option value="-1"> Select </option> </td> </tr> </table> 但这只适用于.NET 4.6,但我的应用程序需要在XP机器上运行。还有另一种方法吗?

AppContext.SetSwitch

2 个答案:

答案 0 :(得分:5)

如果您的目标版本低于.NET 4.6并且希望在没有app.config的情况下执行此操作,则可以执行此操作:

var type = Type.GetType("System.AppContext");
if (type != null) {
    var setSwitch = type.GetMethod("SetSwitch", BindingFlags.Public | BindingFlags.Static);
    setSwitch.Invoke(null, new object[] { "Switch.System.IO.UseLegacyPathHandling", false });
    setSwitch.Invoke(null, new object[] { "Switch.System.IO.BlockLongPaths", false });
}

这样,如果您的应用程序当前在.NET 4.6+上运行(其中AppContext可用,并且这些开关实际上有效) - 您可以设置它们,否则什么也不做。

答案 1 :(得分:-2)

var type = Type.GetType("System.AppContext");
if (type != null) {
    var setSwitch = type.GetMethod("SetSwitch", BindingFlags.Public | BindingFlags.Static);
    setSwitch.Invoke(null, new object[] { "Switch.System.IO.UseLegacyPathHandling", false });
    setSwitch.Invoke(null, new object[] { "Switch.System.IO.BlockLongPaths", false });
}

我已经在我的应用程序中使用了此代码,但是对于长路径,应该将setSwitch内的值与之进行比较