TempFile.cs 1.25 KB
Newer Older
1 2 3 4 5 6 7
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Google.ProtocolBuffers.ProtoGen
{
Jon Skeet's avatar
Jon Skeet committed
8 9 10 11 12 13 14 15 16 17
    class ProtoFile : TempFile
    {
        public ProtoFile(string filename, string contents)
            : base(filename, contents)
        {
        }
    }
    class TempFile : IDisposable
    {
        private string tempFile;
18

Jon Skeet's avatar
Jon Skeet committed
19 20 21 22
        public static TempFile Attach(string path) 
        {
            return new TempFile(path, null);
        }
23

Jon Skeet's avatar
Jon Skeet committed
24 25 26 27 28 29 30
        protected TempFile(string filename, string contents) {
            tempFile = filename;
            if (contents != null)
            {
                File.WriteAllText(tempFile, contents, new UTF8Encoding(false));
            }
        }
31

Jon Skeet's avatar
Jon Skeet committed
32 33 34 35
        public TempFile(string contents)
            : this(Path.GetTempFileName(), contents)
        {
        }
36

Jon Skeet's avatar
Jon Skeet committed
37
        public string TempPath { get { return tempFile; } }
38

Jon Skeet's avatar
Jon Skeet committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
        public void ChangeExtension(string ext)
        {
            string newFile = Path.ChangeExtension(tempFile, ext);
            File.Move(tempFile, newFile);
            tempFile = newFile;
        }

        public void Dispose()
        {
            if (File.Exists(tempFile))
            {
                File.Delete(tempFile);
            }
        }
    }
54
}