我有一个对象集合,它们也包含集合,我想将它们保存到文件中并稍后阅读。这是Windows 10 UNIVERSAL应用程序.net 4.5和VB
我是这样的,但是它给出了错误“不应该在UI线程上执行同步操作。考虑在Task.Run中包装此方法。”}
Public Sub SaveSpRules(FileName As String)
Dim fs As New FileStream(FileName, FileMode.OpenOrCreate)
Dim serializer As New XmlSerializer(GetType(Rule))
Dim writer As New StreamWriter(fs)
serializer.Serialize(writer, r)
End Sub
规则是类,集合名为SpecialRulesCollection,此代码编译但不起作用
感谢任何帮助。请注意,对于Windows 10 Universal应用程序,我无法编译BinaryWriter,因为它不包含在Universal应用程序中。
答案 0 :(得分:0)
谢谢Oyiwai,我找到了答案
Public Async Sub SaveSpRules(FileName As String,t As Object)
Dim myfile As StorageFile
myfile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("test.dat", CreationCollisionOption.ReplaceExisting)
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(Rules))
KnownTypeList.Add(GetType(Rule))
Dim r As Streams.IRandomAccessStream
r = Await myfile.OpenAsync(FileAccessMode.ReadWrite)
Using outStream As Streams.IOutputStream = r.GetOutputStreamAt(0)
Dim serializer As New DataContractSerializer(GetType(Rules), KnownTypeList)
serializer.WriteObject(outStream.AsStreamForWrite(), t)
Await outStream.FlushAsync()
outStream.Dispose()
r.Dispose()
End Using
End Sub
Public Async Sub ReadFile()
Dim t As New Collection(Of Rule)
Dim myfile As Stream
Dim r As New Rules
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(Rules))
Dim serializer As New DataContractSerializer(GetType(Rules), KnownTypeList)
myfile = Await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("test.dat")
r = serializer.ReadObject(myfile)
End Sub