<Window
x:Class="DataIntegrityTools.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DataIntegrityTools"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="#161616">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Outras partes da Grid podem ficar nas linhas 0 e 1 -->
<Grid x:Name="ViewFiles" Grid.Row="2" Background="#161616" HorizontalAlignment="Center" VerticalAlignment="Center">
<ListView x:Name="FilesListView" Width="90%" Height="80%" SelectionMode="None">
<ListView.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Selecionar" Grid.Column="0" Margin="5" FontWeight="Bold" Foreground="White"/>
<TextBlock Text="Nome" Grid.Column="1" Margin="5" FontWeight="Bold" Foreground="White"/>
<TextBlock Text="Hash" Grid.Column="2" Margin="5" FontWeight="Bold" Foreground="White"/>
<TextBlock Text="Tamanho" Grid.Column="3" Margin="5" FontWeight="Bold" Foreground="White"/>
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:FileItem">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{x:Bind IsSelected, Mode=TwoWay}" Grid.Column="0" Margin="5"
VerticalAlignment="Center" HorizontalAlignment="Center"/>
<TextBlock Text="{x:Bind Name}" Grid.Column="1" Margin="5" Foreground="White" VerticalAlignment="Center"/>
<TextBlock Text="{x:Bind Hash}" Grid.Column="2" Margin="5" Foreground="White" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"/>
<TextBlock Text="{x:Bind Size}" Grid.Column="3" Margin="5" Foreground="White" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
<!-- Botão Gerar File -->
<Button Content="Gerar File" Grid.Row="2" VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="0,0,0,20"
Click="GerarFile_Click"/>
</Grid>
</Window>
#include "pch.h"
#include "MainWindow.xaml.h"
#if __has_include("MainWindow.g.cpp")
#include "MainWindow.g.cpp"
#endif
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Storage.FileProperties.h>
#include <winrt/Windows.Storage.Pickers.h>
#include <Shlwapi.h>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <wincrypt.h> // Para cálculo de hash
using namespace winrt;
using namespace Microsoft::UI::Xaml;
using namespace DataIntegrityTools;
using namespace Windows::Storage;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml::Data;
namespace winrt::DataIntegrityTools::implementation
{
MainWindow::MainWindow()
{
InitializeComponent();
// Vincular a coleção de arquivos ao ListView
FilesListView.ItemsSource(Files());
// Carregar os arquivos ao iniciar a janela
LoadFiles();
}
winrt::Windows::Foundation::Collections::IObservableVector<FileItem> MainWindow::Files()
{
return m_files;
}
void MainWindow::LoadFiles()
{
if (m_folderPath.empty())
{
// Defina aqui o caminho da pasta desejada
m_folderPath = L"C:\\Caminho\\Para\\Sua\\Pasta"; // Substitua pelo caminho real
}
// Extensões de arquivos a serem incluídas
std::vector<std::wstring> extensions = { L".dll", L".exe", L".asi", L".m3d" };
std::wstring folderPath = m_folderPath.c_str();
WIN32_FIND_DATA findFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
std::wstring searchPath = folderPath + L"\\*";
hFind = FindFirstFile(searchPath.c_str(), &findFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
// Tratar erro de abertura da pasta
return;
}
do
{
std::wstring fileName = findFileData.cFileName;
if (fileName == L"." || fileName == L"..")
continue;
// Verificar a extensão do arquivo
size_t pos = fileName.find_last_of(L'.');
if (pos == std::wstring::npos)
continue;
std::wstring ext = fileName.substr(pos);
bool validExt = false;
for (const auto& e : extensions)
{
if (_wcsicmp(ext.c_str(), e.c_str()) == 0)
{
validExt = true;
break;
}
}
if (!validExt)
continue;
std::wstring fullPath = folderPath + L"\\" + fileName;
// Obter o tamanho do arquivo
LARGE_INTEGER size;
HANDLE hFile = CreateFile(fullPath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
if (GetFileSizeEx(hFile, &size))
{
// Converter tamanho para string
std::wstring sizeStr = std::to_wstring(size.QuadPart) + L" bytes";
// Calcular o hash
winrt::hstring hash = ComputeFileHash(fullPath);
// Adicionar à coleção
FileItem item;
item.Name(winrt::to_hstring(fileName));
item.Hash(hash);
item.Size(winrt::to_hstring(sizeStr));
item.IsSelected(true); // Checkbox ativado por padrão
m_files.Append(item);
}
CloseHandle(hFile);
}
} while (FindNextFile(hFind, &findFileData) != 0);
FindClose(hFind);
}
winrt::hstring MainWindow::ComputeFileHash(const std::wstring& filePath)
{
// Implementação do cálculo de hash utilizando SHA-256
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
BYTE buffer[4096];
DWORD bytesRead = 0;
std::wstring hexHash;
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
return L"Erro de hash";
}
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash))
{
CryptReleaseContext(hProv, 0);
return L"Erro de hash";
}
HANDLE hFile = CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return L"Erro de hash";
}
BOOL result;
do
{
result = ReadFile(hFile, buffer, sizeof(buffer), &bytesRead, NULL);
if (bytesRead > 0)
{
if (!CryptHashData(hHash, buffer, bytesRead, 0))
{
CloseHandle(hFile);
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return L"Erro de hash";
}
}
} while (result && bytesRead > 0);
CloseHandle(hFile);
if (!result)
{
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return L"Erro de hash";
}
BYTE hashData[32]; // SHA-256 produz 32 bytes
DWORD hashSize = sizeof(hashData);
if (!CryptGetHashParam(hHash, HP_HASHVAL, hashData, &hashSize, 0))
{
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return L"Erro de hash";
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
// Converter o hash para string hexadecimal
std::wstringstream ss;
ss << std::hex << std::uppercase;
for (DWORD i = 0; i < hashSize; ++i)
{
ss << std::setw(2) << std::setfill(L'0') << (int)hashData[i];
}
return winrt::to_hstring(ss.str());
}
void MainWindow::GerarFile_Click(IInspectable const& sender, RoutedEventArgs const& e)
{
// Coletar os arquivos selecionados
std::vector<FileItem> selectedFiles;
for (auto&& item : m_files)
{
if (item.IsSelected())
{
selectedFiles.push_back(item);
}
}
if (selectedFiles.empty())
{
// Opcional: mostrar uma mensagem informando que nenhuma seleção foi feita
return;
}
// Construir o conteúdo do arquivo INI
std::wstring iniContent;
for (const auto& file : selectedFiles)
{
iniContent += L"File Name: " + file.Name().c_str() + L" " + file.Hash().c_str() + L"\n";
}
// Definir o caminho para salvar o arquivo INI
// Por exemplo, na mesma pasta do executável
wchar_t exePath[MAX_PATH];
GetModuleFileName(NULL, exePath, MAX_PATH);
std::wstring path(exePath);
size_t pos = path.find_last_of(L"\\/");
std::wstring directory = (pos != std::wstring::npos) ? path.substr(0, pos) : L".";
std::wstring iniPath = directory + L"\\rTales.ini";
// Salvar o arquivo
std::wofstream iniFile(iniPath);
if (iniFile.is_open())
{
iniFile << iniContent;
iniFile.close();
// Opcional: informar sucesso ao usuário
}
else
{
// Tratar erro ao salvar o arquivo
}
}
}