This repository was archived by the owner on Feb 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringAsTempFile.cs
More file actions
83 lines (73 loc) · 2.73 KB
/
StringAsTempFile.cs
File metadata and controls
83 lines (73 loc) · 2.73 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
using System;
using System.IO;
using System.Threading;
namespace Nodebridge
{
/// <summary>
/// Makes it easier to pass script files to Node in a way that's sure to clean up after the process exits.
/// </summary>
/// https://github.com/aspnet/JavaScriptServices/blob/master/src/Microsoft.AspNetCore.NodeServices/Util/StringAsTempFile.cs
internal sealed class StringAsTempFile : IDisposable
{
private bool _disposedValue;
private bool _hasDeletedTempFile;
private readonly object _fileDeletionLock = new object();
private readonly IDisposable _applicationLifetimeRegistration;
/// <summary>
/// Create a new instance of <see cref="StringAsTempFile"/>.
/// </summary>
/// <param name="content">The contents of the temporary file to be created.</param>
/// <param name="applicationStoppingToken">A token that indicates when the host application is stopping.</param>
public StringAsTempFile(string content, CancellationToken applicationStoppingToken)
{
FileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".js");
File.WriteAllText(FileName, content);
// Because .NET finalizers don't reliably run when the process is terminating, also
// add event handlers for other shutdown scenarios.
_applicationLifetimeRegistration = applicationStoppingToken.Register(EnsureTempFileDeleted);
}
/// <summary>
/// Specifies the filename of the temporary file.
/// </summary>
public string FileName { get; }
/// <summary>
/// Disposes the instance and deletes the associated temporary file.
/// </summary>
public void Dispose()
{
DisposeImpl(true);
GC.SuppressFinalize(this);
}
private void DisposeImpl(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// Dispose managed state
_applicationLifetimeRegistration.Dispose();
}
EnsureTempFileDeleted();
_disposedValue = true;
}
}
private void EnsureTempFileDeleted()
{
lock (_fileDeletionLock)
{
if (!_hasDeletedTempFile)
{
File.Delete(FileName);
_hasDeletedTempFile = true;
}
}
}
/// <summary>
/// Implements the finalization part of the IDisposable pattern by calling Dispose(false).
/// </summary>
~StringAsTempFile()
{
DisposeImpl(false);
}
}
}