TempFile.cs (3595B)
1 // ----------------------------------------------------------------------------- 2 // <copyright file="TempFile.cs" company="Microsoft Corporation"> 3 // Copyright (c) Microsoft Corporation. Licensed under the MIT License. 4 // </copyright> 5 // ----------------------------------------------------------------------------- 6 7 namespace Microsoft.WinGet.Client.Engine.Helpers 8 { 9 using System; 10 using System.IO; 11 12 /// <summary> 13 /// Creates a temporary file in the user's temporary directory. 14 /// </summary> 15 internal class TempFile : IDisposable 16 { 17 private readonly bool cleanup; 18 19 private bool disposed = false; 20 21 /// <summary> 22 /// Initializes a new instance of the <see cref="TempFile"/> class. 23 /// </summary> 24 /// <param name="fileName">Optional file name. If null, creates a random file name.</param> 25 /// <param name="deleteIfExists">Delete file if already exists. Default true.</param> 26 /// <param name="content">Optional content. If not null or empty, creates file and writes to it.</param> 27 /// <param name="cleanup">Deletes file at disposing time. Default true.</param> 28 public TempFile( 29 string? fileName = null, 30 bool deleteIfExists = true, 31 string? content = null, 32 bool cleanup = true) 33 { 34 if (fileName is null) 35 { 36 this.FileName = Path.GetRandomFileName(); 37 this.FullPath = Path.Combine(Path.GetTempPath(), this.FileName); 38 } 39 else 40 { 41 this.FileName = fileName; 42 var randomDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); 43 Directory.CreateDirectory(randomDir); 44 this.FullPath = Path.Combine(randomDir, this.FileName); 45 } 46 47 if (deleteIfExists && File.Exists(this.FullPath)) 48 { 49 File.Delete(this.FullPath); 50 } 51 52 if (!string.IsNullOrWhiteSpace(content)) 53 { 54 this.CreateFile(content); 55 } 56 57 this.cleanup = cleanup; 58 } 59 60 /// <summary> 61 /// Gets the file name. 62 /// </summary> 63 public string FileName { get; } 64 65 /// <summary> 66 /// Gets the full path. 67 /// </summary> 68 public string FullPath { get; } 69 70 /// <summary> 71 /// IDisposable.Dispose. 72 /// </summary> 73 public void Dispose() 74 { 75 this.Dispose(true); 76 GC.SuppressFinalize(this); 77 } 78 79 /// <summary> 80 /// Creates the file. 81 /// </summary> 82 /// <param name="content">Content.</param> 83 public void CreateFile(string? content = null) 84 { 85 if (content is null) 86 { 87 using var fs = File.Create(this.FullPath); 88 } 89 else 90 { 91 File.WriteAllText(this.FullPath, content); 92 } 93 } 94 95 /// <summary> 96 /// Protected disposed. 97 /// </summary> 98 /// <param name="disposing">Disposing.</param> 99 protected virtual void Dispose(bool disposing) 100 { 101 if (!this.disposed) 102 { 103 if (this.cleanup && File.Exists(this.FullPath)) 104 { 105 File.Delete(this.FullPath); 106 } 107 108 this.disposed = true; 109 } 110 } 111 } 112 }