Set Static .NET Property Values
Set System.Environment.CurrentDirectory Static Property
You can set a static property using the NET.setStaticProperty function.
For example, set the CurrentDirectory property, which is a static read-write property of the System.Environment class.
First, set your current folder.
cd("C:\Work")
saveDir = System.Environment.CurrentDirectory
saveDir = C:\work
This example creates a folder temp in the current folder and changes the CurrentDirectory property to the new folder. Then set the CurrentDirectory property to temp.
newDir = char(saveDir) + "\temp"; if ~isfolder(newDir) mkdir(newDir) end NET.setStaticProperty("System.Environment.CurrentDirectory",newDir) System.Environment.CurrentDirectory
ans = C:\work\temp
Restore the original CurrentDirectory property value.
NET.setStaticProperty("System.Environment.CurrentDirectory",saveDir)
System.Environment.CurrentDirectory
ans = C:\work
Do Not Use ClassName.PropertyName Syntax for Static Properties
If you try to use the
ClassName.PropertyName syntax to set a static property,
MATLAB® creates a struct array instead of setting the
property.
For example, this code replaces the System namespace
with a structure named System.
saveDir = System.Environment.CurrentDirectory;
newDir = char(saveDir) + "\temp";
System.Environment.CurrentDirectory = newDir;
whos
Name Size Bytes Class System 1x1 679 struct newDir 1x2 364 string saveDir 1x1 8 System.String
Now when you try to use a member of the System
namespace, MATLAB accesses System as a structure instead. For
example:
oldDate = System.DateTime(2025,3,1);
Unrecognized field name "DateTime".
Restore your access to the .NET System namespace by
clearing the System structure variable. Then set the
CurrentDirectory property using the appropriate
function.
clear System NET.setStaticProperty("System.Environment.CurrentDirectory",saveDir) System.DateTime(2025,3,1)