using System;
using System.IO;
using static Vanara.PInvoke.Kernel32;
namespace Vanara.PInvoke.Tests
{
/// Creates a unique temporary file in the %APPDATA%\Temp folder and deletes it when disposed.
///
public class TempFile : IDisposable
{
/// The default value inserted into the file if not overridden by constructor parameter.
public const string tmpstr = @"Temporary";
/// Initializes a new instance of the class and retrieves a handle to the file.
/// The desired access.
/// The share mode.
/// The creation disposition.
/// The flags and attributes.
public TempFile(Kernel32.FileAccess dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition = FileMode.OpenOrCreate,
FileFlagsAndAttributes dwFlagsAndAttributes = FileFlagsAndAttributes.FILE_ATTRIBUTE_NORMAL) : this(string.Empty) =>
hFile = CreateFile(FullName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero);
/// Initializes a new instance of the class with the specified contents.
///
/// The text inserted into the file. If this value is , the file is not created on disk.
///
public TempFile(string contents = tmpstr)
{
FullName = Path.GetTempFileName();
if (contents is null)
File.Delete(FullName);
else if (contents != string.Empty)
File.WriteAllText(FullName, contents);
}
/// Initializes a new instance of the class with the specified extension and contents.
/// The file extension.
///
/// The text inserted into the file. If this value is , the file is not created on disk.
///
public TempFile(string ext, string contents = tmpstr)
{
FullName = Path.Combine(Path.GetTempPath(), $"tmp{Guid.NewGuid():N}.{ext.TrimStart('.')}");
if (contents is not null)
File.WriteAllText(FullName, contents);
}
/// Gets the full path of the temporary file.
/// The full path of the temporary file.
public string FullName { get; }
///
/// Gets the file handle if created with the constructor.
///
/// The file handle.
public SafeHFILE hFile { get; }
/// Releases unmanaged and - optionally - managed resources.
///
void IDisposable.Dispose()
{
hFile?.Dispose();
if (File.Exists(FullName))
File.Delete(FullName);
}
}
}