-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathTemporaryFile.cs
More file actions
96 lines (85 loc) · 2.53 KB
/
TemporaryFile.cs
File metadata and controls
96 lines (85 loc) · 2.53 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.IO;
using System.Threading.Tasks;
using Waher.Events;
namespace Waher.Runtime.Temporary
{
/// <summary>
/// Class managing the contents of a temporary file. When the class is disposed, the temporary file is deleted.
/// </summary>
public class TemporaryFile : FileStream
{
/// <summary>
/// Default buffer size, in bytes.
/// </summary>
public const int DefaultBufferSize = 16384;
private string fileName;
private bool deleteWhenDisposed = true;
/// <summary>
/// Class managing the contents of a temporary file. When the class is disposed, the temporary file is deleted.
/// </summary>
public TemporaryFile()
: this(Path.GetTempFileName(), DefaultBufferSize)
{
}
/// <summary>
/// Class managing the contents of a temporary file. When the class is disposed, the temporary file is deleted.
/// </summary>
/// <param name="FileName">Name of temporary file. Call <see cref="Path.GetTempFileName()"/> to get a new temporary file name.</param>
public TemporaryFile(string FileName)
: this(FileName, DefaultBufferSize)
{
}
/// <summary>
/// Class managing the contents of a temporary file. When the class is disposed, the temporary file is deleted.
/// </summary>
/// <param name="FileName">Name of temporary file. Call <see cref="Path.GetTempFileName()"/> to get a new temporary file name.</param>
/// <param name="BufferSize">Buffer size.</param>
public TemporaryFile(string FileName, int BufferSize)
: base(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, BufferSize, FileOptions.RandomAccess)
{
this.fileName = FileName;
}
/// <summary>
/// File Name.
/// </summary>
public string FileName => this.fileName;
/// <summary>
/// Delete file when object is disposed.
/// </summary>
public bool DeleteWhenDisposed
{
get => this.deleteWhenDisposed;
set => this.deleteWhenDisposed = value;
}
/// <summary>
/// Disposes of the object, and deletes the temporary file.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!(this.fileName is null))
{
if (this.deleteWhenDisposed)
DeleteFile(FileName);
this.fileName = null;
}
}
private static void DeleteFile(string FileName)
{
try
{
if (File.Exists(FileName))
File.Delete(FileName);
}
catch (IOException) // File locked. Wait a while and try again.
{
Task.Delay(10000).ContinueWith((T) => DeleteFile(FileName));
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
}
}