Приложение FileProperties
25C# и .NET --- Многопоточность и файлы --- Приложение FileProperties
В этой статье для примера рассматривается создание приложения на C# под названием FileProperties. Это приложение обладает простым пользовательским интерфейсом, который позволяет перемещаться по файловой системе и просматривать информацию о времени создания, последнего доступа, последнего изменения и размере хранящихся в ней файлов.
Реализуем данную программу на WPF используя следующий пользовательский интерфейс:
<Window x:Class="FileProperties.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Свойства файлов" MinWidth="500"
WindowStartupLocation="CenterScreen"
SizeToContent="WidthAndHeight">
<StackPanel Margin="10">
<TextBlock Margin="10,0,5,0">Введите путь к папке и нажмите <Run Foreground="DarkOrange">Отобразить</Run></TextBlock>
<Grid Margin="10,5,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="auto" SharedSizeGroup="myBtnGroup" x:Name="cd1"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox x:Name="textBoxInput" VerticalContentAlignment="Center" FontSize="12">C:\</TextBox>
<Button x:Name="buttonDisplay" Content="Отобразить" Grid.Column="1" Padding="5"
Margin="5,0,5,0" Click="buttonDisplay_Click"></Button>
</Grid>
<GroupBox Header="Проводник">
<StackPanel>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition SharedSizeGroup="myBtnGroup" Width="auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox x:Name="textBoxFolder" VerticalContentAlignment="Center" FontSize="12" Foreground="Gray"></TextBox>
<Button x:Name="buttonUp" Content="Вверх" Grid.Column="1" Padding="5"
Width="{Binding ElementName=buttonDisplay, Path=ActualWidth}"
Margin="5,0,0,0" Click="buttonUp_Click"></Button>
</Grid>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock>Файлы</TextBlock>
<TextBlock Grid.Column="1">Папки</TextBlock>
<ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="1">
<ListBox MinHeight="200" MaxHeight="300" Margin="0,5,5,0" x:Name="listBoxFiles"
SelectionChanged="listBoxFiles_SelectionChanged"></ListBox>
</ScrollViewer>
<ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="1" Grid.Column="1">
<ListBox MinHeight="200" MaxHeight="300" SelectionChanged="listBoxFolders_SelectionChanged"
Margin="0,5,5,0" x:Name="listBoxFolders"></ListBox>
</ScrollViewer>
</Grid>
<GroupBox Header="Свойства файла">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Путь к файлу:</TextBlock>
<TextBox Grid.Column="1" Margin="5,0,0,0" x:Name="textBoxFileName"
Height="{Binding ElementName=textBoxInput, Path=ActualHeight}"
FontSize="12" VerticalContentAlignment="Center"></TextBox>
</Grid>
<Grid Margin="0,5,0,0">
<Grid.Resources>
<Style TargetType="TextBox">
<Setter Property="Margin" Value="0,5,5,5"></Setter>
<Setter Property="Height" Value="{Binding ElementName=textBoxInput, Path=ActualHeight}"></Setter>
<Setter Property="VerticalContentAlignment" Value="Center"></Setter>
<Setter Property="FontSize" Value="12"></Setter>
<Setter Property="IsReadOnly" Value="true"></Setter>
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock>Размер файла</TextBlock>
<TextBox x:Name="textBoxFileSize" Grid.Row="1"></TextBox>
<TextBlock Grid.Column="1">Время создания: </TextBlock>
<TextBox Grid.Row="1" Grid.Column="1" x:Name="textBoxCreationTime"></TextBox>
<TextBlock Grid.Row="2">Изменен</TextBlock>
<TextBlock Grid.Row="2" Grid.Column="1">Открыт</TextBlock>
<TextBox Grid.Row="3" x:Name="textBoxLastWriteTime"></TextBox>
<TextBox Grid.Row="3" Grid.Column="1" x:Name="textBoxLastAccessTime"></TextBox>
</Grid>
</StackPanel>
</GroupBox>
</StackPanel>
</GroupBox>
</StackPanel>
</Window>
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace FileProperties
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Путь к папке
private string currentFolderPath;
public MainWindow()
{
InitializeComponent();
}
// Метод, для очистки содержимого всех элементов управления
protected void ClearAllFields()
{
listBoxFolders.Items.Clear();
listBoxFiles.Items.Clear();
textBoxFolder.Text = "";
textBoxFileName.Text = "";
textBoxCreationTime.Text = "";
textBoxLastAccessTime.Text = "";
textBoxLastWriteTime.Text = "";
textBoxFileSize.Text = "";
}
// Метод, для отображения информации о файле
protected void DisplayFileInfo(string fileFullName)
{
FileInfo fi = new FileInfo(fileFullName);
if (!fi.Exists)
{
throw new FileNotFoundException("Файл "+fileFullName+" не найден :(");
}
textBoxFileName.Text = fi.Name;
textBoxFileSize.Text = (fi.Length / 1024).ToString() + " kb";
textBoxCreationTime.Text = fi.CreationTime.ToLongTimeString();
textBoxLastAccessTime.Text = fi.LastAccessTime.ToLongTimeString();
textBoxLastWriteTime.Text = fi.LastWriteTime.ToLongTimeString();
}
// Метод, для отображения содержимого папок в ListBox
protected void DisplayFolderList(string folder)
{
DirectoryInfo di = new DirectoryInfo(folder);
if (!di.Exists)
throw new DirectoryNotFoundException("Папка не найдена :(");
ClearAllFields();
textBoxFolder.Text = di.FullName;
currentFolderPath = di.FullName;
// Отображение списков всех подпапок и файлов
foreach (DirectoryInfo d in di.GetDirectories())
listBoxFolders.Items.Add(d.Name);
foreach (FileInfo f in di.GetFiles())
listBoxFiles.Items.Add(f.Name);
}
private void buttonDisplay_Click(object sender, RoutedEventArgs e)
{
try
{
string folderPath = textBoxInput.Text;
DirectoryInfo di = new DirectoryInfo(folderPath);
if (di.Exists)
{
DisplayFolderList(di.FullName);
return;
}
FileInfo fi = new FileInfo(folderPath);
if (fi.Exists)
{
DisplayFolderList(fi.Directory.FullName);
int i = listBoxFiles.Items.IndexOf(fi.Name);
listBoxFiles.SelectedIndex = i;
return;
}
throw new FileNotFoundException("Файл или папка с таким именем не существует");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void listBoxFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
string selectionString = listBoxFiles.SelectedItem.ToString();
string fullFileName = Path.Combine(currentFolderPath, selectionString);
DisplayFileInfo(fullFileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void listBoxFolders_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
string selectionString = listBoxFolders.SelectedItem.ToString();
string fullPathName = Path.Combine(currentFolderPath, selectionString);
DisplayFolderList(fullPathName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonUp_Click(object sender, RoutedEventArgs e)
{
try
{
string folderPath = new FileInfo(currentFolderPath).DirectoryName;
DisplayFolderList(folderPath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
