New to Telerik UI for WinFormsStart a free 30-day trial

How to Highlight Locked Files and Display Tooltip for these Files.

Updated over 6 months ago

Environment

Product VersionProductAuthor
2022.2.511File Dialogs for WinFormsDinko Krastev

Description

A common requirement in File Dialogs is to highlight a file that has been locked by another process. In the next section we will demonstrate how we can do that.

Solution

To highlight a file that has been locked by another process, we can subscribe to the Shown() event of the file dialogs. For the purpose of this example we are going to use RadOpenFileDialog and set the ViewType of the ExplorerControl to DeailtsView. Then we can subscribe to the VisualItemFormatting event of the RadListView part. Inside the event handler we can check if a file is locked by trying to open it. Here we can change the BackColor of the VisualItem if we can't open it.

filedialogs-highlight-locked-files

C#

public Form1()
{
    InitializeComponent();
    RadOpenFileDialog openFileDialog = new RadOpenFileDialog();
    openFileDialog.OpenFileDialogForm.Shown += OpenFileDialogForm_Shown;
    openFileDialog.ShowDialog();
}

private void OpenFileDialogForm_Shown(object sender, EventArgs e)
{
    var dialog = sender as RadOpenFileDialogForm;
    var listView = dialog.ExplorerControl.FileBrowserListView;
    listView.VisualItemFormatting += ListView_VisualItemFormatting;
    dialog.ExplorerControl.FileBrowserListView.ViewType = ListViewType.DetailsView;           
}

private void ListView_VisualItemFormatting(object sender, ListViewVisualItemEventArgs e)
{
    if (e.VisualItem is DetailListViewVisualItem)
    {
        var visualItem = e.VisualItem as DetailListViewVisualItem;
        var fileInfoWrapper = visualItem.Data.DataBoundItem as FileInfoWrapper;
        if (fileInfoWrapper != null)
        {
            var isLocked = IsFileLocked(new FileInfo(fileInfoWrapper.Path));
            if (isLocked)
            {
                e.VisualItem.BackColor = Color.Red;
                e.VisualItem.ToolTipText = "The File is used in another process";
            }
        }
    }
}
public bool IsFileLocked(FileInfo file)
{
    var stream = (FileStream)null;
    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException ex)
    {
        //handle the exception your way
        return true;
    }
    finally
    {
        if (stream != null)
        {
            stream.Close();
        }
    }
    return false;
}

In this article
EnvironmentDescriptionSolution
Not finding the help you need?
Contact Support