Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 保证重写文件,在进程失败时保留旧副本?_C#_.net - Fatal编程技术网

C# 保证重写文件,在进程失败时保留旧副本?

C# 保证重写文件,在进程失败时保留旧副本?,c#,.net,C#,.net,保证用新文件重写旧文件的最佳方法是什么?我需要检测此操作是否失败,并使用有效文件的最新已知版本 在我的代码中,我正在写入.temp文件,因为它可能超过100MB,删除原始文件,并将temp重命名为原始文件。还有一些恢复步骤 我担心文件移动操作,因为我不知道正在执行哪些步骤 File.Move(_fullTempPath, _fullPath); public class JsonFileCache { private readonly string _path; priva

保证用新文件重写旧文件的最佳方法是什么?我需要检测此操作是否失败,并使用有效文件的最新已知版本

在我的代码中,我正在写入.temp文件,因为它可能超过100MB,删除原始文件,并将temp重命名为原始文件。还有一些恢复步骤

我担心文件移动操作,因为我不知道正在执行哪些步骤

File.Move(_fullTempPath, _fullPath); 


public class JsonFileCache
{
    private readonly string _path;
    private string _fileName;

    private string _fullPath
    {
       get { return _path + _fileName; }
    }

    private string _fullTempPath
    {
        get { return _path + _fileName + ".temp"; }
    }

    public JsonFileCache(string fileName, string cacheDirectory)
    {
        _fileName = fileName;
        _path = cacheDirectory;
    }

    public T GetOrCreate<T>() where T : new()
    {
        CreateDirectoryIfDoesNotExists(_path);

        if (File.Exists(_fullTempPath) && !File.Exists(_fullPath))
        {
            File.Move(_fullTempPath, _fullPath);
        }

        if (!File.Exists(_fullPath))
        {
            File.Create(_fullPath);
            return new T();
        }

        var jsonString = File.ReadAllText(_fullPath);

        if (string.IsNullOrEmpty(jsonString))
        {
            return new T();
        }

        var data = jsonString.FromJson<T>();

        return data;
    }

    private void CreateDirectoryIfDoesNotExists(string path)
    {
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    }

    public void Save<T>(T data)
    {
        CreateDirectoryIfDoesNotExists(_path);
        var jsonString = data.ToJson();
        File.WriteAllText(_fullTempPath, jsonString);
        File.Delete(_fullPath);
        File.Move(_fullTempPath, _fullPath);
    }
}

使用临时名称写入,如果成功删除旧名称,并重命名新名称,我认为try/catch是您要寻找的,请使用它继续您的写入/删除/移动操作。如果出现问题,您将得到一个异常。如果计算机崩溃,可能没有异常,或者这在IIS中运行,并且应用程序池被回收,我已检查事件,文件。移动不会创建任何新文件temp dir。。。。。如果source dest与windows rename Commands的id相同,那么如果您停止重新发明wheel并使用支持版本控制任何源代码管理系统或事务(如传统DBs)的现有系统(即MSSQL),该怎么办?因为类的名称是JsonFileCache,而不是DB,它需要非常快,每10秒发送5x100MB需要一些时间。Esent Persistent Dictionary是另一个选项,但它需要对现有代码进行更多更改才能使用它,文件缓存是最快的实现,它的工作速度非常快