-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathLazyComponentStream.cs
61 lines (51 loc) · 1.79 KB
/
LazyComponentStream.cs
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
namespace Microsoft.ComponentDetection.Common;
using System;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.Extensions.Logging;
/// <inheritdoc />
public class LazyComponentStream : IComponentStream
{
private readonly FileInfo fileInfo;
private readonly ILogger logger;
private readonly Lazy<byte[]> fileBuffer;
/// <summary>
/// Initializes a new instance of the <see cref="LazyComponentStream"/> class.
/// </summary>
/// <param name="fileInfo">The file information.</param>
/// <param name="pattern">The pattern.</param>
/// <param name="logger">The logger.</param>
public LazyComponentStream(FileInfo fileInfo, string pattern, ILogger logger)
{
this.Pattern = pattern;
this.Location = fileInfo.FullName;
this.fileInfo = fileInfo;
this.logger = logger;
this.fileBuffer = new Lazy<byte[]>(this.SafeOpenFile);
}
/// <inheritdoc />
public Stream Stream => new MemoryStream(this.fileBuffer.Value);
/// <inheritdoc />
public string Pattern { get; set; }
/// <inheritdoc />
public string Location { get; set; }
private byte[] SafeOpenFile()
{
try
{
using var fs = this.fileInfo.OpenRead();
var buffer = new byte[this.fileInfo.Length];
fs.Read(buffer, 0, (int)this.fileInfo.Length);
return buffer;
}
catch (UnauthorizedAccessException e)
{
this.logger.LogWarning(e, "Unauthorized access exception caught when trying to open {FileName}", this.fileInfo.FullName);
}
catch (Exception e)
{
this.logger.LogWarning(e, "Unhandled exception caught when trying to open {FileName}", this.fileInfo.FullName);
}
return [];
}
}