As mentioned in the comments, you cannot move the file because it is still being used by some process. That in the case is your own program, which opened it to do the search and did not de-link it. So it is important to define the scope of the operation with the using
that will make the Dispose()
of the resource at the end.
Another flaw in your logic is if (input.IndexOf(palavra) > 1)
, if the file starts with the word you are searching for your index will 0
and it will not be detected. Also, you are exposed to failure in the detection by box variation and this can be solved with the method ToLowerInvariant()
You also do not need to assign values to variables that you will only use once. Mainly the contents of the file because you don’t need to scroll through it or manipulate it later. If you do not need to know the position of the word, it is not necessary to fetch its index, just know if it is present.
See the example below:
var textoBusca = "bola";
var origem = @"c:\Temp\arquivos\";
var destino = @"C:\Temp\arquivos\validos\";
foreach (var arquivo in Directory.GetFiles(origem, "*.txt"))
{
bool contemTexto = false;
using (StreamReader re = File.OpenText(arquivo))
contemTexto = re.ReadToEnd().ToLowerInvariant()
.Contains(textoBusca.ToLowerInvariant());
if (contemTexto)
File.Move(arquivo, destino + Path.GetFileName(arquivo));
}
Exactly what is the problem?
– Augusto Vasques
I can’t get him to search the phrase inside the files and move all the files that have this word.
– Thiago
probably won’t be able to move an open file
– Ricardo Pontual
Save in a list the names of the files where you found the text and perform the operation of
Move
after the end of the readings. Do not forget the clauseusing
or do the Dispose of your Readers– Leandro Angelo
@Leandroangelo helps me Lz, to much lost :(, I started practicing a little while ago, what should I add in this code that I made to work?
– Thiago
But what exactly is your doubt? Ricardo has already shown what the mistake is and I have presented some solutions... I even think only the
using
can already solve your problem– Leandro Angelo