aboutsummaryrefslogtreecommitdiff
path: root/csharp/src/ProtoGen.Test/TempFile.cs
blob: 74a183f5a83dc0ba767b770ba3fe994463bc0453 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Google.ProtocolBuffers.ProtoGen
{
    internal class ProtoFile : TempFile
    {
        public ProtoFile(string filename, string contents)
            : base(filename, contents)
        {
        }
    }

    internal class TempFile : IDisposable
    {
        private string tempFile;

        public static TempFile Attach(string path)
        {
            return new TempFile(path, null);
        }

        protected TempFile(string filename, string contents)
        {
            tempFile = filename;
            if (contents != null)
            {
                File.WriteAllText(tempFile, contents, new UTF8Encoding(false));
            }
        }

        public TempFile(string contents)
            : this(Path.GetTempFileName(), contents)
        {
        }

        public string TempPath
        {
            get { return tempFile; }
        }

        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);
            }
        }
    }
}