C# - Save object to JSON file

前端 未结 2 777
盖世英雄少女心
盖世英雄少女心 2021-01-13 20:00

I\'m writing a Windows Phone Silverlight app. I want to save an object to a JSON file. I\'ve written the following piece of code.

string jsonFile = JsonConve         


        
2条回答
  •  执念已碎
    2021-01-13 20:18

    I use these. Shoud work for you as well.

        public async Task SaveFile(string fileName, string data)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile local =
                System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
    
            if (!local.DirectoryExists("MyDirectory"))
                local.CreateDirectory("MyDirectory");
    
            using (var isoFileStream =
                    new System.IO.IsolatedStorage.IsolatedStorageFileStream(
                        string.Format("MyDirectory\\{0}.txt", fileName),
                        System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite,
                            local))
            {
                using (var isoFileWriter = new System.IO.StreamWriter(isoFileStream))
                {
                    await isoFileWriter.WriteAsync(data);
                }
            }
        }
    
        public async Task LoadFile(string fileName)
        {
            string data;
    
            System.IO.IsolatedStorage.IsolatedStorageFile local =
                System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
    
            using (var isoFileStream =
                    new System.IO.IsolatedStorage.IsolatedStorageFileStream
                        (string.Format("MyDirectory\\{0}.txt", fileName),
                        System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read,
                        local))
            {
                using (var isoFileReader = new System.IO.StreamReader(isoFileStream))
                {
                    data = await isoFileReader.ReadToEndAsync();
                }
            }
    
            return data;
        }
    

提交回复
热议问题