Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Switch in Code

Tags:

c#

.net

I'm trying to embed the following switch setting in my console application but I need the app.config to not be necessary. Is there another way to set this switch within the app?

I have come across AppContext.SetSwitch but this is only available in .NET 4.6, but my app will need to run on XP machines. Is there another way of doing this?

<runtime>
  <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
</runtime>
like image 976
windowsgm Avatar asked Sep 10 '26 10:09

windowsgm


1 Answers

If you target version lower than .NET 4.6 and want to do that without app.config, you can do this:

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 });
}

That way, if your application currently runs on .NET 4.6+ (where AppContext is available and where those switches will actually have any effect) - you set them, otherwise do nothing.

like image 192
Evk Avatar answered Sep 12 '26 01:09

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!