Safe stream update of file

前端 未结 8 1350
别那么骄傲
别那么骄傲 2020-11-30 14:37

We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:

         


        
相关标签:
8条回答
  • 2020-11-30 15:34

    Transactional NTFS on Windows Vista or later might be useful for your scenario.

    0 讨论(0)
  • 2020-11-30 15:34

    I found it useful to wrap this pattern in it's own class.

    class Program {
        static void Main( string[] args ) {
            using( var ft = new FileTransaction( @"C:\MyDir\MyFile.txt" ) )
            using( var sw = new StreamWriter( ft.TempPath ) ) {
                sw.WriteLine( "Hello" );
                ft.Commit();
            }
        }
    }
    
    public class FileTransaction :IDisposable {
        public string TempPath { get; private set; }
        private readonly string filePath;
    
        public FileTransaction( string filePath ) {
            this.filePath = filePath;
            this.TempPath = Path.GetTempFileName();
        }
    
        public void Dispose() {
            if( TempPath != null ) {
                try {
                    File.Delete( TempPath );
                }
                catch { }
            }
        }
    
        public void Commit() {
            try {
                var oldPath = filePath + ".old";
                File.Move( filePath, oldPath );
            }
            catch {}
    
            File.Move( TempPath, filePath );
    
            TempPath = null;
        }
    }
    
    0 讨论(0)
提交回复
热议问题