C# - Save object to JSON file

前端 未结 2 773
盖世英雄少女心
盖世英雄少女心 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<string> 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;
        }
    
    0 讨论(0)
  • 2021-01-13 20:25

    The problem is that you're not closing the stream.

    File I/O in Windows have buffers at the operating system level, and .NET might even implement buffers at the API level, which means that unless you tell the class "Now I'm done", it will never know when to ensure those buffers are propagated all the way down to the platter.

    You should rewrite your code just slightly, like this:

    using (StreamWriter str = new StreamWriter(isoStream))
    {
        str.Write(jsonFile);
    }
    

    using (...) { ... } will ensure that when the code leaves the block, the { ... } part, it will call IDisposable.Dispose on the object, which in this case will flush the buffers and close the underlying file.

    0 讨论(0)
提交回复
热议问题