Problem generating a path with Path.Combine

3

I have the following problem, which has a bit of a head ... :( I am formatting 3 string to form a path with Path.Combine (C # and WPF) in the first string has its origin in a TextBox (this is the problematic), the other two I get from an object.

My code is as follows:

string origen;
string destino;

List<Archivos> listaArchivosDescarga = DataTableToObjeto.ConvertirDataTableEnListaObjetos<Archivos>(archivos.BuscarPorVersion(1));

foreach(Archivos archivo in listaArchivosDescarga)
{
     origen = Path.Combine(archivo.RutaServidor, archivo.NombreArchivoVirtual);
     destino = Path.Combine(TbxRutaDestinoCliente.Text, archivo.Ruta, archivo.NombreArchivoFisico);

     File.Copy(origen, destino, true);
}

The problem is that the second Combine that generates the destination of the file, passes completely from the TextBox content and at the time of formatting the route, only "sees" the last two variables of this line (file.Route and file. PhysicalFileName)

Within TextBox I have for example: "C:\pruebas" , in variable archivo.Ruta , I have "\BIN\" and in archivo.NombreArchivoFisico : "cmdline.cmd" , the result of Combine is: "\BIN\cmdline.cmd" .

Please, someone can give me a cable.

Thanks and best regards!

    
asked by Javi Rodríguez 28.06.2018 в 16:17
source

2 answers

3

According to the documentation of System.IO.Path.Combin e :

  

If one of the specified routes is a zero-length string, this   method returns the other route. S i path2 contains an absolute path,   this method returns path2 .

This means that when you add \ in front of path 2 \BIN\ , it is interpreted as absolute path.

Try to delete the backslash in path2, that is, delete the backslash at the beginning. Instead of \BIN\ , it would be BIN\ :

System.IO.Path.Combine(@"C:\pruebas", @"\BIN\", "cmd.exe") // "\bin\cmd.exe"
System.IO.Path.Combine(@"C:\pruebas", @"BIN\", "cmd.exe") // "C:\pruebas\bin\cmd.exe"
    
answered by 28.06.2018 / 16:46
source
5

As you clarify in your comments, one of the parties, specifically archivo.Ruta is \BIN\ . The problem is that it is an absolute route, so the above is discarded.

The solution is simple. If that property always starts with backslash, you can do a Substring :

destino = Path.Combine(TbxRutaDestinoCliente.Text, archivo.Ruta.Substring(1), archivo.NombreArchivoFisico");

If you're not sure, you can always replace all the backslashes of that property:

destino = Path.Combine(TbxRutaDestinoCliente.Text, archivo.Ruta.Replace("\", ""), archivo.NombreArchivoFisico");
    
answered by 28.06.2018 в 16:50