Загрузка данных


djsjdkdkdkdk


<Window x:Class="MaterialExplorer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:local="clr-namespace:MaterialExplorer"
        Title="Material Explorer"
        Height="700"
        Width="1100"
        MinHeight="500"
        MinWidth="800"
        WindowStartupLocation="CenterScreen"
        Background="{DynamicResource MaterialDesign.Brush.Background}"
        TextElement.Foreground="{DynamicResource MaterialDesign.Brush.Foreground}"
        TextElement.FontWeight="Regular"
        TextElement.FontSize="14"
        FontFamily="{materialDesign:MaterialDesignFont}"
        Style="{StaticResource MaterialDesignWindow}">

    <Window.Resources>
        <local:StringToPackIconKindConverter x:Key="IconConverter"/>
        <Style x:Key="SideMenuButton" TargetType="Button" BasedOn="{StaticResource MaterialDesignFlatButton}">
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="Padding" Value="16,10"/>
            <Setter Property="Margin" Value="4,2"/>
            <Setter Property="Height" Value="40"/>
            <Setter Property="Foreground" Value="{DynamicResource MaterialDesign.Brush.Foreground}"/>
        </Style>
        <Style x:Key="SideMenuHeader" TargetType="TextBlock">
            <Setter Property="FontWeight" Value="SemiBold"/>
            <Setter Property="FontSize" Value="12"/>
            <Setter Property="Opacity" Value="0.7"/>
            <Setter Property="Margin" Value="16,16,16,6"/>
            <Setter Property="Foreground" Value="{DynamicResource MaterialDesign.Brush.Foreground}"/>
        </Style>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <Border Grid.Row="0"
                Background="{DynamicResource MaterialDesign.Brush.Card.Background}"
                BorderBrush="{DynamicResource MaterialDesign.Brush.Divider}"
                BorderThickness="0,0,0,1"
                Padding="8,6">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>

                <StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
                    <Button x:Name="BackButton" Click="BackButton_Click"
                            Style="{StaticResource MaterialDesignIconButton}"
                            ToolTip="Назад" Margin="2,0" IsEnabled="False">
                        <materialDesign:PackIcon Kind="ArrowLeft" Width="22" Height="22"/>
                    </Button>
                    <Button x:Name="ForwardButton" Click="ForwardButton_Click"
                            Style="{StaticResource MaterialDesignIconButton}"
                            ToolTip="Вперёд" Margin="2,0" IsEnabled="False">
                        <materialDesign:PackIcon Kind="ArrowRight" Width="22" Height="22"/>
                    </Button>
                    <Button x:Name="UpButton" Click="UpButton_Click"
                            Style="{StaticResource MaterialDesignIconButton}"
                            ToolTip="Вверх" Margin="2,0">
                        <materialDesign:PackIcon Kind="ArrowUp" Width="22" Height="22"/>
                    </Button>
                    <Button x:Name="RefreshButton" Click="RefreshButton_Click"
                            Style="{StaticResource MaterialDesignIconButton}"
                            ToolTip="Обновить" Margin="2,0">
                        <materialDesign:PackIcon Kind="Refresh" Width="22" Height="22"/>
                    </Button>
                </StackPanel>

                <TextBox x:Name="PathTextBox" KeyDown="PathTextBox_KeyDown"
                         Grid.Column="1" Margin="12,0,12,0"
                         VerticalAlignment="Center"
                         materialDesign:HintAssist.Hint="Путь..."
                         materialDesign:TextFieldAssist.HasClearButton="True"
                         Style="{StaticResource MaterialDesignOutlinedTextBox}"
                         FontSize="13" Height="36"/>

                <StackPanel Grid.Column="2" Orientation="Horizontal" VerticalAlignment="Center">
                    <TextBox x:Name="SearchTextBox" Width="200"
                             VerticalAlignment="Center"
                             materialDesign:HintAssist.Hint="Поиск..."
                             materialDesign:TextFieldAssist.HasClearButton="True"
                             Style="{StaticResource MaterialDesignOutlinedTextBox}"
                             FontSize="13" Height="36" Margin="0,0,4,0"/>
                    <Button x:Name="SearchButton" Click="SearchButton_Click"
                            Style="{StaticResource MaterialDesignIconButton}"
                            ToolTip="Поиск">
                        <materialDesign:PackIcon Kind="Magnify" Width="22" Height="22"/>
                    </Button>
                </StackPanel>
            </Grid>
        </Border>

        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="240" MinWidth="180"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Border Grid.Column="0"
                    Background="{DynamicResource MaterialDesign.Brush.Card.Background}"
                    BorderBrush="{DynamicResource MaterialDesign.Brush.Divider}"
                    BorderThickness="0,0,1,0">
                <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
                    <StackPanel Margin="0,8,0,16">
                        <TextBlock Text="БЫСТРЫЙ ДОСТУП" Style="{StaticResource SideMenuHeader}"/>
                        <Button x:Name="DesktopButton" Click="DesktopButton_Click" Style="{StaticResource SideMenuButton}">
                            <StackPanel Orientation="Horizontal">
                                <materialDesign:PackIcon Kind="DesktopClassic" Width="20" Height="20" Margin="0,0,12,0"/>
                                <TextBlock Text="Рабочий стол" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                        <Button x:Name="DocumentsButton" Click="DocumentsButton_Click" Style="{StaticResource SideMenuButton}">
                            <StackPanel Orientation="Horizontal">
                                <materialDesign:PackIcon Kind="FileDocument" Width="20" Height="20" Margin="0,0,12,0"/>
                                <TextBlock Text="Документы" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                        <Button x:Name="DownloadsButton" Click="DownloadsButton_Click" Style="{StaticResource SideMenuButton}">
                            <StackPanel Orientation="Horizontal">
                                <materialDesign:PackIcon Kind="Download" Width="20" Height="20" Margin="0,0,12,0"/>
                                <TextBlock Text="Загрузки" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                        <Button x:Name="PicturesButton" Click="PicturesButton_Click" Style="{StaticResource SideMenuButton}">
                            <StackPanel Orientation="Horizontal">
                                <materialDesign:PackIcon Kind="Image" Width="20" Height="20" Margin="0,0,12,0"/>
                                <TextBlock Text="Изображения" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                        <Button x:Name="MusicButton" Click="MusicButton_Click" Style="{StaticResource SideMenuButton}">
                            <StackPanel Orientation="Horizontal">
                                <materialDesign:PackIcon Kind="Music" Width="20" Height="20" Margin="0,0,12,0"/>
                                <TextBlock Text="Музыка" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                        <TextBlock Text="ДЕЙСТВИЯ" Style="{StaticResource SideMenuHeader}" Margin="16,24,16,6"/>
                        <Button x:Name="NewFolderButton" Click="NewFolderButton_Click" Style="{StaticResource SideMenuButton}">
                            <StackPanel Orientation="Horizontal">
                                <materialDesign:PackIcon Kind="FolderPlus" Width="20" Height="20" Margin="0,0,12,0"
                                                         Foreground="{DynamicResource MaterialDesign.Brush.Primary}"/>
                                <TextBlock Text="Новая папка" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                        <Button x:Name="DeleteButton" Click="DeleteButton_Click" Style="{StaticResource SideMenuButton}">
                            <StackPanel Orientation="Horizontal">
                                <materialDesign:PackIcon Kind="Delete" Width="20" Height="20" Margin="0,0,12,0" Foreground="#EF5350"/>
                                <TextBlock Text="Удалить" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                    </StackPanel>
                </ScrollViewer>
            </Border>

            <GridSplitter Grid.Column="1" Width="4" HorizontalAlignment="Center"
                          VerticalAlignment="Stretch" Background="Transparent"/>

            <Grid Grid.Column="2">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Border Grid.Row="0" Padding="16,10"
                        Background="{DynamicResource MaterialDesign.Brush.Background}">
                    <TextBlock x:Name="CurrentPathText" Text="Файлы и папки"
                               FontSize="16" FontWeight="Medium" VerticalAlignment="Center"/>
                </Border>
                <ListView x:Name="FilesListView"
                          MouseDoubleClick="FilesListView_MouseDoubleClick"
                          SelectionChanged="FilesListView_SelectionChanged"
                          Grid.Row="1" Margin="8,0,8,8"
                          Background="Transparent" BorderThickness="0"
                          ScrollViewer.HorizontalScrollBarVisibility="Auto"
                          ScrollViewer.VerticalScrollBarVisibility="Auto"
                          materialDesign:ListViewAssist.ListViewItemPadding="12,8">
                    <ListView.View>
                        <GridView>
                            <GridViewColumn Header="Имя" Width="320">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Horizontal">
                                            <materialDesign:PackIcon Kind="{Binding Icon, Converter={StaticResource IconConverter}}"
                                                                     Width="20" Height="20" Margin="0,0,10,0"
                                                                     VerticalAlignment="Center"
                                                                     Foreground="{DynamicResource MaterialDesign.Brush.Primary}"/>
                                            <TextBlock Text="{Binding Name}" VerticalAlignment="Center"
                                                       TextTrimming="CharacterEllipsis"/>
                                        </StackPanel>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="Тип" Width="140" DisplayMemberBinding="{Binding Type}"/>
                            <GridViewColumn Header="Размер" Width="110" DisplayMemberBinding="{Binding Size}"/>
                            <GridViewColumn Header="Дата изменения" Width="160" DisplayMemberBinding="{Binding Date}"/>
                        </GridView>
                    </ListView.View>
                </ListView>
            </Grid>
        </Grid>

        <Border Grid.Row="2"
                Background="{DynamicResource MaterialDesign.Brush.Card.Background}"
                BorderBrush="{DynamicResource MaterialDesign.Brush.Divider}"
                BorderThickness="0,1,0,0" Padding="12,6">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <TextBlock x:Name="StatusText" Text="Готово" VerticalAlignment="Center" Opacity="0.8" FontSize="12"/>
                <TextBlock Grid.Column="1" x:Name="ItemsCountText" Text="0 элементов"
                           VerticalAlignment="Center" Opacity="0.8" FontSize="12"/>
            </Grid>
        </Border>
    </Grid>
</Window>


using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Input;
using IOPath = System.IO.Path;

namespace MaterialExplorer
{
    public partial class MainWindow : Window
    {
        private string currentPath = "";
        private readonly Stack<string> backHistory = new Stack<string>();
        private readonly Stack<string> forwardHistory = new Stack<string>();

        public MainWindow()
        {
            InitializeComponent();
            currentPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            LoadDirectory(currentPath);
        }

        private void LoadDirectory(string path, bool addToHistory = false)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    MessageBox.Show("Папка не существует.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (addToHistory && currentPath != path)
                {
                    backHistory.Push(currentPath);
                    forwardHistory.Clear();
                }

                currentPath = path;
                PathTextBox.Text = currentPath;

                var items = new List<FileItem>();

                foreach (string directory in Directory.GetDirectories(currentPath))
                {
                    try
                    {
                        DirectoryInfo info = new DirectoryInfo(directory);
                        items.Add(new FileItem
                        {
                            Name = info.Name,
                            Type = "Папка",
                            Size = "",
                            Date = info.LastWriteTime.ToString("dd.MM.yyyy HH:mm"),
                            FullPath = info.FullName,
                            IsDirectory = true,
                            Icon = "Folder"
                        });
                    }
                    catch { }
                }

                foreach (string file in Directory.GetFiles(currentPath))
                {
                    try
                    {
                        FileInfo info = new FileInfo(file);
                        items.Add(new FileItem
                        {
                            Name = info.Name,
                            Type = GetFileType(info.Extension),
                            Size = FormatSize(info.Length),
                            Date = info.LastWriteTime.ToString("dd.MM.yyyy HH:mm"),
                            FullPath = info.FullName,
                            IsDirectory = false,
                            Icon = GetFileIcon(info.Extension)
                        });
                    }
                    catch { }
                }

                FilesListView.ItemsSource = items;
                ItemsCountText.Text = $"{items.Count} элементов";
                StatusText.Text = currentPath;
                CurrentPathText.Text = new DirectoryInfo(currentPath).Name;
                BackButton.IsEnabled = backHistory.Count > 0;
                ForwardButton.IsEnabled = forwardHistory.Count > 0;
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Нет доступа к этой папке.", "Доступ запрещён", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            if (backHistory.Count == 0)
                return;

            forwardHistory.Push(currentPath);
            string path = backHistory.Pop();
            LoadDirectory(path);
        }

        private void ForwardButton_Click(object sender, RoutedEventArgs e)
        {
            if (forwardHistory.Count == 0)
                return;

            backHistory.Push(currentPath);
            string path = forwardHistory.Pop();
            LoadDirectory(path);
        }

        private void UpButton_Click(object sender, RoutedEventArgs e)
        {
            DirectoryInfo? parent = Directory.GetParent(currentPath);
            if (parent != null)
                LoadDirectory(parent.FullName, true);
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            LoadDirectory(currentPath);
        }

        private void PathTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                string path = PathTextBox.Text.Trim();
                if (Directory.Exists(path))
                    LoadDirectory(path, true);
                else
                    MessageBox.Show("Указанная папка не найдена.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        private void DesktopButton_Click(object sender, RoutedEventArgs e)
        {
            LoadDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), true);
        }

        private void DocumentsButton_Click(object sender, RoutedEventArgs e)
        {
            LoadDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), true);
        }

        private void DownloadsButton_Click(object sender, RoutedEventArgs e)
        {
            string path = IOPath.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
                "Downloads");
            LoadDirectory(path, true);
        }

        private void PicturesButton_Click(object sender, RoutedEventArgs e)
        {
            LoadDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), true);
        }

        private void MusicButton_Click(object sender, RoutedEventArgs e)
        {
            LoadDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), true);
        }

        private void NewFolderButton_Click(object sender, RoutedEventArgs e)
        {
            string name = "Новая папка";
            string path = IOPath.Combine(currentPath, name);
            int number = 1;

            while (Directory.Exists(path))
            {
                path = IOPath.Combine(currentPath, $"{name} ({number})");
                number++;
            }

            try
            {
                Directory.CreateDirectory(path);
                LoadDirectory(currentPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (FilesListView.SelectedItem is not FileItem item)
            {
                MessageBox.Show("Выберите файл или папку.");
                return;
            }

            MessageBoxResult result = MessageBox.Show(
                $"Удалить «{item.Name}»?",
                "Подтверждение",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result != MessageBoxResult.Yes)
                return;

            try
            {
                if (item.IsDirectory)
                    Directory.Delete(item.FullPath, true);
                else
                    File.Delete(item.FullPath);

                LoadDirectory(currentPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка удаления");
            }
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            string search = PathTextBox.Text;

            if (!Directory.Exists(search))
                return;

            var items = Directory.GetFiles(search, "*", SearchOption.AllDirectories)
                .Select(file =>
                {
                    FileInfo info = new FileInfo(file);
                    return new FileItem
                    {
                        Name = info.Name,
                        Type = GetFileType(info.Extension),
                        Size = FormatSize(info.Length),
                        Date = info.LastWriteTime.ToString("dd.MM.yyyy HH:mm"),
                        FullPath = info.FullName,
                        IsDirectory = false,
                        Icon = GetFileIcon(info.Extension)
                    };
                })
                .ToList();

            FilesListView.ItemsSource = items;
            ItemsCountText.Text = $"Найдено: {items.Count}";
        }

        private void FilesListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (FilesListView.SelectedItem is not FileItem item)
                return;

            if (item.IsDirectory)
            {
                LoadDirectory(item.FullPath, true);
            }
            else
            {
                try
                {
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = item.FullPath,
                        UseShellExecute = true
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка");
                }
            }
        }

        private void FilesListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        }

        private string GetFileType(string extension)
        {
            extension = extension.ToLower();
            return extension switch
            {
                ".txt" => "Текстовый файл",
                ".doc" => "Документ Word",
                ".docx" => "Документ Word",
                ".pdf" => "PDF документ",
                ".jpg" => "Изображение",
                ".jpeg" => "Изображение",
                ".png" => "Изображение",
                ".gif" => "Изображение",
                ".mp3" => "Аудио",
                ".wav" => "Аудио",
                ".mp4" => "Видео",
                ".avi" => "Видео",
                ".zip" => "Архив",
                ".rar" => "Архив",
                ".exe" => "Приложение",
                ".cs" => "C# файл",
                ".xaml" => "XAML файл",
                _ => "Файл"
            };
        }

        private string GetFileIcon(string extension)
        {
            extension = extension.ToLower();
            return extension switch
            {
                ".txt" => "FileDocument",
                ".doc" or ".docx" => "FileWord",
                ".pdf" => "FilePdfBox",
                ".jpg" or ".jpeg" or ".png" or ".gif" => "FileImage",
                ".mp3" or ".wav" => "FileMusic",
                ".mp4" or ".avi" => "FileVideo",
                ".zip" or ".rar" => "ZipBox",
                ".exe" => "Application",
                ".cs" or ".xaml" => "FileCode",
                _ => "File"
            };
        }

        private string FormatSize(long bytes)
        {
            if (bytes < 1024)
                return $"{bytes} Б";
            if (bytes < 1024 * 1024)
                return $"{bytes / 1024.0:F1} KB";
            if (bytes < 1024 * 1024 * 1024)
                return $"{bytes / 1024.0 / 1024:F1} MB";
            return $"{bytes / 1024.0 / 1024 / 1024:F1} GB";
        }
    }
}


jdjdjdkdkdk