ManagedFile.h (1355B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #pragma once 4 #include <wil/resource.h> 5 #include <filesystem> 6 7 namespace AppInstaller::Utility 8 { 9 // Struct that holds a file handle and may perform additional operations on exit 10 struct ManagedFile 11 { 12 ManagedFile() = default; 13 14 ManagedFile(const ManagedFile&) = delete; 15 ManagedFile& operator=(const ManagedFile&) = delete; 16 17 ManagedFile(ManagedFile&&) = default; 18 ManagedFile& operator=(ManagedFile&&) = default; 19 20 HANDLE GetFileHandle() const { return m_fileHandle.get(); } 21 const std::filesystem::path& GetFilePath() const { return m_filePath; } 22 23 // Always creates a new write locked file at the path given. desiredAccess is passed to CreateFile call. 24 static ManagedFile CreateWriteLockedFile(const std::filesystem::path& path, DWORD desiredAccess, bool deleteOnExit); 25 26 // Always opens an existing file at the path given with write locked. desiredAccess is passed to CreateFile call. 27 static ManagedFile OpenWriteLockedFile(const std::filesystem::path& path, DWORD desiredAccess); 28 29 ~ManagedFile(); 30 31 private: 32 std::filesystem::path m_filePath; 33 wil::unique_handle m_fileHandle; 34 bool m_deleteFileOnExit = false; 35 }; 36 }