2
I have a problem using the foreach
to traverse a array of strings.
This component is a search button to select files, it selects and writes the address of the file into a array of strings, i created a repeat loop to check if the same file was selected twice, but the second run of loop results in an exception.
How the exception is generated:
- I select two files, they are stored in array hassle-free.
- I again select the same two files to test the method.
- The first check is done successfully, the program recognizes that the file is already in the list and does not add it.
- When checking the second file the exception is generated.
List<string> ListPath = new List<string>(); // Array
string File; // Arquivo
private void Search_Click(object sender, EventArgs e)
{
OpenFileDialog AbrirArquivo = new OpenFileDialog(); //Instância
AbrirArquivo.Multiselect = true; // habilita a multseleção de arquivos
if (AbrirArquivo.ShowDialog() == DialogResult.OK) // ao pressionar ok
{
foreach (var File in AbrirArquivo.FileNames) // para cada arquivo no array
{
if(ListPath.Count == 0) // se a lista for vazia
{
ListPath.Add(File); //adiciona o primeiro elemento
}
else // se não for vazia, agora ele verifica se já existe
{
foreach(var item in ListPath) //Onde ocorre a Exception
{
if(item == File) //se o item da lista for igual ao caminho do arquivo
{
continue; // pula para o próximo e não adiciona na lista
}
else
{
ListPath.Add(File); // se não, adiciona.
}
}
}
}
}
PathText.Text = (ListPath.Count + " Arquivos selecionados");
// mostra em um textBox quantos arquivos foram selecionados.
}
Super useful, I didn’t know.
– Query