【问题标题】:Settings File is corrupted as well as the backup file设置文件以及备份文件已损坏
【发布时间】:2019-01-26 00:22:35
【问题描述】:
    /// <summary>
    /// Save settings to config file. Create backup of current settings
    /// </summary>
    public void SaveSettings()
    {
        Directory.CreateDirectory(CONFIG_DIRECTORY);

        // move current settings file to backup
        if (File.Exists(SettingsFile))
        {
            if (File.Exists(SettingsBackupFile)) // delete prev backup
                File.Delete(SettingsBackupFile);

            File.Move(SettingsFile, SettingsBackupFile);
        }

        // Create new settings file
        using (var f = (TextWriter)File.CreateText(SettingsFile))
        {
            f.WriteLine(JsonConvert.SerializeObject(_settings, Formatting.Indented));
            f.Close();
        }
    }

我将当前设置文件重命名为 .bak 文件,然后替换当前设置文件。我这样做是因为如果用户在下载过程中关闭电源,我的文件可能/将会损坏。我认为如果设置文件已损坏,我可以从备份中读取此设计模式,但备份文件也已损坏。

【问题讨论】:

  • 如果SettingsFile 被破坏,你认为File.Move(SettingsFile, SettingsBackupFile); 会做什么?
  • my files can/will become corrupted if the user does a power shutdown during a download 但是这样做的用户应该得到发生在他们身上的一切。
  • @NoneoftheAbove 对于生活在电力供应不可靠地区的最终用户,您的看法如此富有同情心。 :)
  • user does a power shutdown 不是停电。
  • @mjwills 你可能是对的。我可能错误地认为如果文件因断电而损坏,那么我的代码将不会执行,因此无法备份最近损坏的文件

标签: c# .net backup corruption file-management


【解决方案1】:

当您写入文件时,数据会进入操作系统回写缓存。当操作系统意外崩溃(断电、蓝屏、VM 终止)时,数据会丢失。典型的症状是文件大小正确但全是零。 (也许尺寸也可能不对,我不知道。)

一般来说,写入一个新文件然后交换新旧文件的想法是一个很好的策略。但是您还需要将数据刷新到磁盘。

FileStream.Flush() 和 StreamWriter.Flush() 这样做。很有可能,您应该添加f.Flush();。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2013-10-24
    • 2021-11-06
    • 2018-06-21
    相关资源
    最近更新 更多