2013-06-22 35 views
1

我无法搞清楚如何将此集合写入文件。我有以下类将IEnumerable <IEnumerable <Point>>写入文件

public static class GeoPolyLines 
{ 
    public static ObservableCollection<Connections> connections = new ObservableCollection<Connections>(); 
} 

public class Connections 
{ 
    public IEnumerable<IEnumerable<Point>> Points { get; set; } 

    public Connections(Point p1, Point p2) 
    { 
     Points = new List<List<Point>> 
     { 
       new List<Point> 
       { 
        p1, p2 
       } 
     }; 
    } 

} 

然后像这样的一堆东西:

GeoPolyLines.connections.Add(new Connections(new Point(GeoLocations.locations[0].Longitude, GeoLocations.locations[0].Latitude), new Point(GeoLocations.locations[1].Longitude, GeoLocations.locations[1].Latitude))); 

所以GeoPolyLines.connections最终将有一堆我要那么写出来的不同位置。 txt文件保存并重新加载,如果我需要的话。但我不知道该怎么做。我有这样的事情:

using (StreamWriter sw = new StreamWriter(filename)) 
{ 
    var enumerator = GeoPolyLines.connections.GetEnumerator(); 

    while (enumerator.MoveNext()) 
    { 

    } 
    sw.Close(); 
} 

回答

3

使用序列化。

写入文件

var serializer = new JavaScriptSerializer(); 

File.WriteAllText(filename, serializer.Serialize(points)); 

,并从文件

var points = serializer.Deserialize<List<Point>>(File.ReadAllText(filename)); 
+0

阅读我仍然是一个noobie但是从我读昨天的序列化不适合静态类工作。但这会工作吗? –

+1

@jimjohnjim'Connections'不是一个静态类。你可以用一行代码序列化GeoPolyLines.connections。 'serializer.Serialize(GeoPolyLines.connection)' – I4V

+0

我得到一个错误,它不能被序列化,因为它不包含无参数的构造函数。 –

相关问题