Check if dynamic named file exists on disk

Asked

Viewed 27 times

2

My program generates an XML file named after the following structure:

C:/wayDosFile/Nameanob_data_nrdeelementosnoxml.xml

At the moment, I’m every time I file and he has the nrDeElementosNoXML other than nrDeElementosNoXML from the existing file, create me another file. Can I use any method to delete the file that is already there before creating a new one? Something like this:

if(File.Exists(@"C:/caminhoDosFicheiro/NOMEQUENAOMUDA_data_*valorDesconhecido*.xml"))
{
    File.Delete(@"C:/caminhoDosFicheiro/NOMEQUENAOMUDA_data_*valorDesconhecido*.xml");
}
  • Before inserting a new one, you want to delete all existing ones that start with "Namean_date_name_"?

  • exactly, I wanted to see if anyone knows a simple technique, because I have some ideas on how to do it, but I’m pretty sure they’re not the best

1 answer

4


Perform the elimination with the help of foreach using the filter desired in GetFiles:

System.IO.DirectoryInfo di = new DirectoryInfo(@"C:/caminhoDosFicheiro");

foreach (FileInfo file in di.GetFiles("NOMEQUENAOMUDA_data_*.xml"))
{
    file.Delete(); 
}

There are other ways too, you can check on this link (Soen).

  • It worked 5*. In my case I had to use this logic to get the right files: di.GetFiles(_key + "_" + globalDateToDownload.Date.ToString("yyy_MM_dd") + "_*.xml")

  • 1

    Try to use interpolation, it is more readable and even, much simpler to write. It would look like this your line: di.GetFiles($"{_key}_{globalDateToDownload.Date.ToString("yyy_MM_dd")}_*.xml") http://answall.com/questions/128043/usando-interpola%C3%A7%C3%A3o-de-string-c-6

  • I didn’t know this technique, it’s much better this way! vlw

Browser other questions tagged

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