Validate if an image name exists in a [closed] path

0

I am trying to validate if an image name obtained from my database exists in a directory. Example:

if(imagen001 ==ruta\xx\imagen001)
{
mensaje: Si tiene imagen
}

In this case I will have many image names in the database, as well as in my image folder.

    
asked by Gonzalo Rios 15.11.2018 в 20:24
source

2 answers

1

If you have the path and the file name independently, you can do the following:

string ruta = @"D:\cursos\ASP.NET";
string archivo = "mi_curso.pdf";
if(File.Exists(ruta+"\"+archivo)){
  Console.WriteLine("Existe el archivo: "+archivo);
} else {
  Console.WriteLine("No existe");
}

Remember to include at the beginning of your file:

using System.IO;

If what you want to know is if a given path as a string contains the name of a specific file you can do the following:

string ruta = @"D:\cursos\ASP.NET\mi_curso.pdf";
string archivo = "mi_curso.pdf";
if(Path.FileName(ruta) == archivo){
  Console.WriteLine("Existe el archivo: "+archivo);
} else {
  Console.WriteLine("No existe");
}

You could do the latter with the IndexOf function that the strings have but you should check that the position found is the last possible one, that is:

string ruta = @"D:\cursos\ASP.NET\mi_curso.pdfs";
string archivo = "mi_curso.pdf";
if (ruta.ToLower().IndexOf(archivo.ToLower()) == ruta.Length - archivo.Length)
{
    Console.WriteLine("Existe el archivo: " + archivo);
}
else
{
   Console.WriteLine("No existe");
 }

If you want to search exactly what the file is named, with case sensitivity; you can remove the .ToLower () wherever it appears in the last example, that is, it would look like this:

if (ruta.IndexOf(archivo) == ruta.Length - archivo.Length)
    
answered by 15.11.2018 / 22:25
source
1

You could upload images to a list in memory using

string[] files = Directory.GetFiles(@"c:\ruta\xx\imagen001", "*.jpg");

List<string> fileNames = files.Select(x=> Path.GetFileName(x)).ToList();

The idea of Select() is to obtain the names of the files since the GetFiles() does not give the full path

then afterwards you iterate the data of the db

//codigo de acceso a la db
var reader = cmd.ExecuteReader();

while(reader.Read()){

   string fileName = reader["fileName"].ToString();

   if(fileNames.Contains(fileName)){
      //existe en la carpeta
   }

}
    
answered by 15.11.2018 в 21:08