Exemplo n.º 1
0
        /// <summary>
        /// Writes a file to disk and creates backup copies if a file with the same name already exists
        /// </summary>
        /// <remarks>Backups are numbered i.e. .1, .2, .3, .4, etc and rotate up as new copies are made (i.e. if .1 exists, it will be renamed .2 and the current one renamed to .1, etc)</remarks>
        private void WriteFileWithBackups(string path, CodeCompileUnit code)
        {
            if (File.Exists(path))             // existing version present; make backups as necessary
            {
                uint maxBackups = Parameters.MaxBackupCopies;

                uint i = maxBackups;
                do                 // find and move existing backups if needed
                {
                    string instanceFileName = path + "." + i.ToString(CultureInfo.InvariantCulture);
                    bool   instanceExists   = File.Exists(instanceFileName);

                    if (i == maxBackups && instanceExists)
                    {
                        File.Delete(instanceFileName);                                                        // truncate a backup that's too old
                    }
                    if (i > 0 && i != maxBackups && instanceExists)
                    {
                        File.Move(instanceFileName, string.Format("{0}.{1}", path, (i + 1).ToString(CultureInfo.InvariantCulture)));                                                                 // move an existing backup up a number in the backups
                    }
                    i--;
                } while (i > 0);

                // move the pre-existing file into the file1.ext position
                File.Move(path, path + ".1");
            }

            // write new file
            File.WriteAllText(path, code.CompileToCSharpSourceCode());
        }