Click here to Skip to main content
15,915,501 members
Articles / Desktop Programming / WPF
Tip/Trick

Simple Way to Make an Interactive File Browser with WPF

Rate me:
Please Sign up or sign in to vote.
1.11/5 (2 votes)
13 Apr 2020CPOL1 min read 9.7K   5  
Easy method in WPF to make an interactive file browser
You want to make a file browser - you have a WPF app that calls API and receives files that you want to show to the user. In this example, we are going to download files on our hard drive, and show them to the user.

Scenario

You want to make a file browser using WPF, or you have a WPF app, that calls API and receives files, that you want to show to the user.

The result would be simple:

Image 1

This is non-MVVM solution, so it would be easy to understand for beginners. In this example, we will discuss the second scenario - we are going to download files on our hard drive, and show them to the user.

Getting Started

Ok, we have an empty WPF application. First, we need to make a model for our files, that we are going to download:

C#
public class Payload
{
    public string url { get; set; }
    public string name { get; set; }
}

Then, we need to create model for our downloaded files:

C#
public class DownloadedFile
{
   public string FileThumbnail { get; set; }
    public string FilePath { get; set; }
    public string FileName { get; set; }
}

In our MainWindow.xaml.cs, paste this code. It will download files and store them in path that we set:

C#
public void GetAttachments() {
           _attachmentPath = "C:/temp/attachments/";

           var downloadStrings = new List<Payload>();
            downloadStrings.Add(new Payload() 
             { url = "https://extend.castsoftware.com/resources/com.castsoftware.wpf.png", 
               name = "Picture.png" });
            downloadStrings.Add(new Payload() 
             { url = "https://www.w3.org/TR/PNG/iso_8859-1.txt", name = "Text file.txt" });
            downloadStrings.Add(new Payload() 
             { url = "https://file-examples.com/wp-content/uploads/2017/02/
                      file_example_XLS_10.xls", name = "Xls file.xls" });

            foreach (Payload file in downloadStrings)
            {
                WebClient webClient = new WebClient();
                {
                    webClient.DownloadFile
                      (file.url, string.Format(_attachmentPath + file.name));
                }
            }
        }

Now we need to load our files to application, and set thumbnails for them. In this case, we will set thumbnails depending on file extension. For this purpose, we need to create folder called "Images" in the root directory of the solution and put several icons there, that can represent file types in UI. The following code does all the stuff with extensions:

C#
public void CollectDownloadedFiles()
{
    FilesCollection = new ObservableCollection<DownloadedFile>();
    
    var folder = new DirectoryInfo(_attachmentPath);
    var downloadedAttachments = folder.GetFiles("*");
    
    foreach (var file in downloadedAttachments)
    {
        //if file == picture, show thumbnail as it is
        if (System.IO.Path.GetExtension(file.FullName) == ".jpg" || 
        System.IO.Path.GetExtension(file.FullName) == ".png" ||
            System.IO.Path.GetExtension(file.FullName) == ".gif" || 
            System.IO.Path.GetExtension(file.FullName) == ".bmp" ||
            System.IO.Path.GetExtension(file.FullName) == ".ico")
        {
            FilesCollection.Add(new DownloadedFile()
            {
                FileThumbnail = file.FullName,
                FilePath = file.FullName,
                FileName = file.Name
            });
        }
        
        //if file != picture, set txt or log thumbnail
        else if (System.IO.Path.GetExtension(file.FullName) == ".txt" || 
        System.IO.Path.GetExtension(file.FullName) == ".log")
        {
            FilesCollection.Add(new DownloadedFile()
            {
                FileThumbnail = "Images/notepad.jpg",
                FilePath = file.FullName,
                FileName = file.Name
            });
        }
        
        //if file is MS Word file, set docx thumbnail
        else if (System.IO.Path.GetExtension(file.FullName) == ".docx")
        {
            FilesCollection.Add(new DownloadedFile()
            {
                FileThumbnail = "Images/doc_word.png",
                FilePath = file.FullName,
                FileName = file.Name
            });
        }
        
        //if file is Excel document, set Excel thumbnail
        else if (System.IO.Path.GetExtension(file.FullName) == ".xls" || 
        System.IO.Path.GetExtension(file.FullName) == ".csv")
        {
            FilesCollection.Add(new DownloadedFile()
            {
                FileThumbnail = "Images/excel.png",
                FilePath = file.FullName,
                FileName = file.Name
            });
        }
        
        //if file has none of our extensions, set the default file thumbnail
        else
        {
            FilesCollection.Add(new DownloadedFile()
            {
                FileThumbnail = "Images/doc_unknown.png",
                FilePath = file.FullName,
                FileName = file.Name
            });
        }
    }
}

And the last coding part - we will add method, that allows us to open files from our file browser:

C#
public void openFile(object sender, MouseButtonEventArgs e)
{
    if (e.ClickCount >= 2)
    {
        foreach (object o in ListBoxFiles.SelectedItems)
        Process.Start((o as DownloadedFile).FilePath);
    }
}

That's all about C#. The last part is to paste listbox element with our bindings to models into MainWindow.xaml:

XML
<ListBox Name="ListBoxFiles"
 ItemsSource="{Binding FilesCollection}"  Margin="0,10,0,0">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel PreviewMouseDown="openAttachment">
                <Image Source="{Binding FileThumbnail}"
                 Width="100" Height="100" Stretch="Uniform"
                 Margin="15" MouseDown="openFile" Cursor="Hand"/>
                <TextBlock Text="{Binding FileName}"
                 HorizontalAlignment="Center" FontFamily="Arial"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

That's it! All files appear in our file browser, with fancy thumbnails (of course, you can replace them with yours) and can be opened by doubleclick.

Git

You can find the whole code on GitHub.

History

  • 13th April, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --