This post is about how to make a File Browser in C# using ListView to contain the file name with icons.
Step 1
Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "FileBrowser" and then click OK
Step 2
Design your file browser form as below.
- <Window
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="DocumentIconDemo.MainWindow"
- Title="MainWindow" Height="500" Width="1000">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="1000*"/>
- <ColumnDefinition Width="89*"/>
- </Grid.ColumnDefinitions>
- <Grid.RowDefinitions>
- <RowDefinition Height="31*"/>
- <RowDefinition Height="288*"/>
- </Grid.RowDefinitions>
- <Button Content="Folder..." Grid.Column="1" Click="Button_Click"/>
- <ScrollViewer Grid.ColumnSpan="2" Grid.Row="1">
- <ListBox x:Name="lstBox" HorizontalContentAlignment="Stretch" Grid.ColumnSpan="2" Grid.Row="1" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionMode="Multiple" >
- <ListBox.Template>
- <ControlTemplate>
- <DockPanel LastChildFill="True">
- <Grid DockPanel.Dock="Top" Height="30">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="25"/>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- </Grid.ColumnDefinitions>
-
- <Label Grid.Column="1">Path</Label>
- <Label Grid.Column="2">Last Creation</Label>
- <Label Grid.Column="3">Last Access</Label>
- <Label Grid.Column="4">Last Modification</Label>
- </Grid>
- <ItemsPresenter></ItemsPresenter>
- </DockPanel>
- </ControlTemplate>
- </ListBox.Template>
- <ListBox.ItemTemplate>
- <DataTemplate>
- <Grid d:DesignWidth="372" d:DesignHeight="46" Margin="0,2">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="25"/>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- </Grid.ColumnDefinitions>
- <Image Source="{Binding ItemIcon}" />
- <Label Content="{Binding ItemText, UpdateSourceTrigger=PropertyChanged,IsAsync=True}" Grid.Column="1"/>
- <Label Content="{Binding LastCreation, UpdateSourceTrigger=PropertyChanged,IsAsync=True}" Grid.Column="2"/>
- <Label Content="{Binding LastAccess, UpdateSourceTrigger=PropertyChanged,IsAsync=True}" Grid.Column="3"/>
- <Label Content="{Binding LastModification, UpdateSourceTrigger=PropertyChanged,IsAsync=True}" Grid.Column="4"/>
- </Grid>
- </DataTemplate>
- </ListBox.ItemTemplate>
- </ListBox>
- </ScrollViewer>
- <TextBlock x:Name="textField" TextWrapping="Wrap" Height="21" Text="TextBlock"/>
- </Grid>
- </Window>
Step 3
Add code to handle your form.
- using System;
- using System.Linq;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media.Imaging;
- using System.IO;
- using System.Threading;
- using System.ComponentModel;
- using System.Reflection;
- using System.Collections.ObjectModel;
-
- namespace DocumentIconDemo
- {
-
-
-
- public partial class MainWindow : Window, INotifyPropertyChanged
- {
- class ListBoxData : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- public void NotifyPropertyChanged(string txt)
- {
-
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(txt));
- PropertyChanged(this, new PropertyChangedEventArgs("DisplayMember"));
- }
- }
- public BitmapSource ItemIcon { get; set; }
- private string itemtext;
- public string ItemText
- {
- get { return itemtext; }
- set
- {
- itemtext = value;
- NotifyPropertyChanged("ItemText");
- }
- }
- private string lastaccess;
- public string LastAccess {
- get { return lastaccess; }
- set
- {
- lastaccess = value;
- NotifyPropertyChanged("LastAccess");
- }
- }
- private string lastcreation;
- public string LastCreation {
- get { return lastcreation; }
- set
- {
- lastcreation = value;
- NotifyPropertyChanged("LastCreation");
- }
- }
- private string lastmodification;
- public string LastModification {
- get { return lastmodification; }
- set
- {
- lastmodification = value;
- NotifyPropertyChanged("LastModification");
- }
- }
- }
- ObservableCollection<ListBoxData> data = new ObservableCollection<ListBoxData>();
- public MainWindow()
- {
- InitializeComponent();
- Loaded += MainWindow_Loaded;
- }
-
- void MainWindow_Loaded(object sender, RoutedEventArgs e)
- {
- textField.Text = "";
- }
- private Thread _thread; string[] dir;
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- var dialog = new System.Windows.Forms.FolderBrowserDialog();
- System.Windows.Forms.DialogResult result = dialog.ShowDialog();
-
- if (result == System.Windows.Forms.DialogResult.OK)
- {
- textField.Text = dialog.SelectedPath;
-
- if (textField.Text == "")
- return;
-
- dir = Directory.GetFiles(textField.Text, "*", SearchOption.AllDirectories);
- _thread = new Thread(() => showSomePeople(lstBox));
- _thread.Start();
- }
- else
- textField.Text = "";
- }
-
- private async void showSomePeople(ListBox lstBox)
- {
- data = GenerateItems();
- await Dispatcher.BeginInvoke(new Action(delegate ()
- {
- lstBox.ItemsSource = data;
- }));
- }
- public event PropertyChangedEventHandler PropertyChanged;
- private void NotifyPropertyChanged(string property)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(property));
- }
- }
- private ObservableCollection<ListBoxData> GenerateItems()
- {
-
- foreach (var filePath in dir)
- {
- var sysicon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
- var bmpSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
- sysicon.Handle,
- System.Windows.Int32Rect.Empty,
- System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
- if (bmpSrc.CanFreeze)
- {
- bmpSrc.Freeze(); /*otherwise we get error - Must create DependencySource on same Thread as the DependencyObject*/
- }
- sysicon.Dispose();
- DateTime creation = File.GetCreationTime(filePath);
- DateTime access = File.GetLastAccessTime(filePath);
- DateTime writeT = File.GetLastWriteTime(filePath);
- data.Add(new ListBoxData() { ItemIcon = bmpSrc, ItemText = filePath, LastCreation = creation.ToString(), LastAccess = access.ToString(), LastModification = writeT.ToString() });
-
- }
- CreateCSVFromGenericList<ListBoxData>(data, "D:\\s.txt");
- return data;
- }
- public static void CreateCSVFromGenericList<T>(ObservableCollection<T> list, string csvCompletePath)
- {
- if (list == null || list.Count == 0) return;
-
-
- Type t = list[0].GetType();
- string newLine = Environment.NewLine;
- if (!Directory.Exists(System.IO.Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(System.IO.Path.GetDirectoryName(csvCompletePath));
- if (!File.Exists(csvCompletePath)) File.Create(csvCompletePath).Close();
-
- using (var sw = new StreamWriter(csvCompletePath))
- {
-
- object o = Activator.CreateInstance(t);
-
- PropertyInfo[] props = o.GetType().GetProperties();
-
-
- sw.Write(string.Join(",", props.Where(d => d.Name != "ItemIcon").Select(d => d.Name).ToArray()) + newLine);
-
- foreach (T item in list)
- {
-
- var row = string.Join("$", props.Where(d => d.Name != "ItemIcon").Select(d => item.GetType()
- .GetProperty(d.Name)
- .GetValue(item, null)
- .ToString())
- .ToArray());
- sw.Write(row + newLine);
- }
- }
- }
- }
- }