FolderFileWatcher.cpp (2577B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #include "pch.h" 4 #include "winget/FolderFileWatcher.h" 5 #include "AppInstallerStrings.h" 6 7 namespace AppInstaller::Utility 8 { 9 FolderFileWatcher::FolderFileWatcher(const std::filesystem::path& path, const std::optional<std::string>& ext) : 10 m_path(path), m_ext(ext), m_changeReader{} 11 { 12 } 13 14 void FolderFileWatcher::Start() 15 { 16 m_files.clear(); 17 m_changeReader = wil::make_folder_change_reader(m_path.c_str(), 18 true, 19 wil::FolderChangeEvents::FileName, 20 [this](wil::FolderChangeEvent changeEvent, PCWSTR filePath) 21 { 22 switch (changeEvent) 23 { 24 // The file was added to the directory. 25 case wil::FolderChangeEvent::Added: 26 // The file was renamed and this is the new name. 27 case wil::FolderChangeEvent::RenameNewName: 28 { 29 std::filesystem::path path(filePath); 30 if (!m_ext.has_value() || Utility::CaseInsensitiveEquals(path.extension().u8string(), *m_ext)) 31 { 32 m_files.emplace(path); 33 } 34 break; 35 } 36 37 // The file was removed from the directory. 38 case wil::FolderChangeEvent::Removed: 39 // The file was renamed and this is the old name. 40 case wil::FolderChangeEvent::RenameOldName: 41 { 42 std::filesystem::path path(filePath); 43 if (!m_ext.has_value() || Utility::CaseInsensitiveEquals(path.extension().u8string(), *m_ext)) 44 { 45 auto it = m_files.find(path); 46 if (it != m_files.cend()) 47 { 48 m_files.erase(it); 49 } 50 } 51 break; 52 } 53 54 // The file was modified. This can be a change in the time stamp or attributes. 55 case wil::FolderChangeEvent::Modified: 56 // A change happens but it got lost. The result of the IoCompletionCallback is ERROR_NOTIFY_ENUM_DIR. 57 case wil::FolderChangeEvent::ChangesLost: 58 default: 59 break; 60 } 61 }); 62 } 63 64 void FolderFileWatcher::Stop() 65 { 66 m_changeReader.reset(); 67 } 68 }