How to create a file filter by dragging in C#

Asked

Viewed 94 times

0

I am implementing the Drag files function to fill a Listbox with the file path.

It works very well, but I would like to put a "filter" making it possible only to import txt.

if it is not txt should appear an error Messagebox to the user.

Follows the Code

private void listBoxArquivosSelecionados_DragOver(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
            e.Effect = DragDropEffects.Link;
        else
            e.Effect = DragDropEffects.None;
    }

    private void listBoxArquivosSelecionados_DragDrop(object sender, DragEventArgs e)
    {
        string[] arquivos = e.Data.GetData(DataFormats.FileDrop) as string[];
        if (arquivos != null)
            listBoxArquivosSelecionados.Items.AddRange(arquivos);
        CarregarStatus();
    }

1 answer

0


Leave it to her, I figured out how to do it, just sweep the vector and if the string contains the pattern ". txt" will be added in the list, if not, display error message, follows code.

private void listBoxArquivosSelecionados_DragDrop(object sender, DragEventArgs e)
    {
        string[] arquivos = e.Data.GetData(DataFormats.FileDrop) as string[];
        if (arquivos != null && arquivos.Any())
        {
            foreach(string arquivo in arquivos)
            {
                if (arquivo.Contains(".txt"))
                    listBoxArquivosSelecionados.Items.Add(arquivo);
                else
                    MessageBox.Show("Carregue apenas arquivos de Texto (.txt)", "Atenção");
            }
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.