TempFile.cs (3412B)
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.Management.Configuration.UnitTests.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 bool disposed = false; 18 private bool cleanup; 19 20 /// <summary> 21 /// Initializes a new instance of the <see cref="TempFile"/> class. 22 /// </summary> 23 /// <param name="fileName">Optional file name. If null, creates a random file name.</param> 24 /// <param name="deleteIfExists">Delete file if already exists. Default true.</param> 25 /// <param name="content">Optional content. If not null or empty, creates file and writes to it.</param> 26 /// <param name="cleanup">Deletes file at disposing time. Default true.</param> 27 public TempFile( 28 string? fileName = null, 29 bool deleteIfExists = true, 30 string? content = null, 31 bool cleanup = true) 32 { 33 if (fileName is null) 34 { 35 this.FileName = Path.GetRandomFileName(); 36 } 37 else 38 { 39 this.FileName = fileName; 40 } 41 42 this.FullFileName = Path.Combine(Path.GetTempPath(), this.FileName); 43 44 if (deleteIfExists && File.Exists(this.FullFileName)) 45 { 46 File.Delete(this.FullFileName); 47 } 48 49 if (!string.IsNullOrWhiteSpace(content)) 50 { 51 this.CreateFile(content); 52 } 53 54 this.cleanup = cleanup; 55 } 56 57 /// <summary> 58 /// Gets the file name. 59 /// </summary> 60 public string FileName { get; } 61 62 /// <summary> 63 /// Gets the full file name. 64 /// </summary> 65 public string FullFileName { get; } 66 67 /// <summary> 68 /// IDisposable.Dispose . 69 /// </summary> 70 public void Dispose() 71 { 72 this.Dispose(true); 73 GC.SuppressFinalize(this); 74 } 75 76 /// <summary> 77 /// Creates the file. 78 /// </summary> 79 /// <param name="content">Content.</param> 80 public void CreateFile(string? content = null) 81 { 82 if (content is null) 83 { 84 using var fs = File.Create(this.FullFileName); 85 } 86 else 87 { 88 File.WriteAllText(this.FullFileName, content); 89 } 90 } 91 92 /// <summary> 93 /// Protected disposed. 94 /// </summary> 95 /// <param name="disposing">Disposing.</param> 96 protected virtual void Dispose(bool disposing) 97 { 98 if (!this.disposed) 99 { 100 if (this.cleanup && File.Exists(this.FullFileName)) 101 { 102 File.Delete(this.FullFileName); 103 } 104 105 this.disposed = true; 106 } 107 } 108 } 109 }