Main Content

Set Static .NET Properties

Set System.Environment.CurrentDirectory Static Property

This example shows how to set a static property using the NET.setStaticProperty function.

The CurrentDirectory property in the System.Environment class is a static, read/write property. The following code creates a folder temp in the current folder and changes the CurrentDirectory property to the new folder.

Set your current folder.

cd('C:\Work')

Set the CurrentDirectory property.

saveDir = System.Environment.CurrentDirectory;
newDir = [char(saveDir) '\temp'];
mkdir(newDir)
NET.setStaticProperty('System.Environment.CurrentDirectory',newDir)
System.Environment.CurrentDirectory
ans = 

C:\Work\temp

Restore the original CurrentDirectory value.

NET.setStaticProperty('System.Environment.CurrentDirectory',saveDir)

Do Not Use ClassName.PropertyName Syntax for Static Properties

This example shows how to mistakenly create a struct array instead of setting a class property.

If you use the ClassName.PropertyName syntax to set a static property, MATLAB® creates a struct array.

The following code creates a structure named System:

saveDir = System.Environment.CurrentDirectory;
newDir = [char(saveDir) '\temp'];
System.Environment.CurrentDirectory = newDir;
whos
  Name         Size            Bytes  Class

  System       1x1               376  struct
  newDir       1x12               24  char
  saveDir      1x1               112  System.String

Try to use a member of the System namespace.

oldDate = System.DateTime(1992,3,1);
Reference to non-existent field 'DateTime'.

To restore your environment, type:

clear System
NET.setStaticProperty('System.Environment.CurrentDirectory',saveDir)