1

VB2012: I am trying to make a clone (not a copy) of the My.Settings class. I tried the DeepClone function found here on SO

Public Function DeepClone(Of T)(ByVal a As T) As T
    Using stream As New System.IO.MemoryStream
        Dim formatter As New BinaryFormatter
        formatter.Serialize(stream, a)
        stream.Position = 0
        Return DirectCast(formatter.Deserialize(stream), T)
    End Using
End Function

but it results in an exception

Type 'MyCompany.MyDept.TestApp.My.MySettings' in Assembly 'TestApp, Version=10.1.0.3, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Being the settings are a class and saved as XML there must be a way to clone them or am I just barking up the wrong tree?

~AGP

sinDizzy
  • 1,300
  • 7
  • 28
  • 60

2 Answers2

0

The easy answer is to not use BinaryFormatter. Use XmlSerializer, DataContractSerializer, or JsonSerializer instead.

(In general the Serializable attribute and the things that use it are deprecated.)

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
  • Tried the XML approach here http://stackoverflow.com/questions/1251277/net-deep-cloning-what-is-the-best-way-to-do-that and it says "MyCompany.MyDept.TestApp.My.MySettings is inaccessible due to its protection level. Only public types can be processed.". So will try another approach. – sinDizzy Jun 16 '16 at 21:16
0

It's not clear why you need a "copy" of the settings. Since My.Settings is a Shared property, the settings it contains are globally accessible. However, since it loads all of its settings from the configuration files the first time a setting property is read, if you really need a second copy in memory, you could just create a new instance of the MySettings class and let it populate itself from file again. For instance, if you had a String setting called ClientName, you could do something like this:

Dim copy As New My.MySettings()
Dim clientName As String = copy.ClientName
Steven Doggart
  • 43,358
  • 8
  • 68
  • 105