在文件中读取、存储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格式的字符串,布布扣,bubuko.com

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

上一篇:Microsoft Web Deployment Tool


下一篇:近期Responsive web design项目经验分享-高分辨率图片处理篇