在文件中读取、存储Json格式的字符串

public class Weather
    {
        static readonly string FilePath = System.Environment.CurrentDirectory + @"\Area.txt";
        public static Models.Area GetCurrentArea()
        {
            var file = new FileInfo(FilePath);
            Models.Area result;
            if (!file.Exists)
            {
                //文件不存在就返回一个默认值,默认是成都
                result = new Models.Area();
                result.ID = 250;
                result.Name = "成都";
                result.ZoneID = 23;
                //area.Zone = new Models.Zone() { ID = 23, Name = "四川" };
                result.AreaCode = "56294";
            }
            else
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Models.Area));
                using (var stream = file.Open(FileMode.Open, FileAccess.Read))
                {
                    result = (Models.Area)ser.ReadObject(stream);                    
                }
            }
            return result;
        }
        public static void SaveCurrentArea(Models.Area area)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Models.Area));
            var file = new FileInfo(FilePath);
            FileStream stream;
            if (file.Exists)
            {
                stream = file.Open(FileMode.Truncate, FileAccess.Write);
            }
            else
            {
                stream = file.Open(FileMode.Create, FileAccess.Write);
            }
            using (stream)
            {
                ser.WriteObject(stream, area);
            }
        }
    }

  

在文件中读取、存储Json格式的字符串,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。