I am trying to create a backup in excel with the data loaded in a DataGridView, but when validating if the file exists it validates wrong. When the file doesn't exist it validates fine and creates it, but when the file already exists it tries to create it the same. I am using visual studio 2017.
This is the code of the method that creates the backup:
public void respaldarInfo(DataGridView dgv)
{
Service_Inscripcion service = new Service_Inscripcion();
DateTimeFormatInfo fecha = new System.Globalization.DateTimeFormatInfo();
//variable para crear o buscar la carpeta donde se va a guardar el respaldo en excel.
//Dentro de la carpeta Respaldo Sport Gym, se van a crear subCarpetas con el formato: "nombre del mes" "año"
string ruta = "C:\\Respaldo Sport Gym\\" + DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Year.ToString();
//variable para darle nombre al excel con el formato: "dia"-"mes"-"año"
string excel = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();
//variable que junta la ruta de la carpeta + la ruta que deberia tener el archivo a crear.
string rutaFinal = ruta + "\\" + excel; ;
IList<DTO_Inscripcion> inscripciones = service.getInscripciones();
if (!Directory.Exists(ruta) && dgv != null)//valida que la carpeta no exista
{
Directory.CreateDirectory(ruta);//en caso de no existir se crea
//Valida que la lista tenga valores para guardar
if (inscripciones != null && inscripciones.Count > 0)
{
crearExcel(dgv,inscripciones,rutaFinal);
}
else
{
MessageBox.Show("No hay datos para guardar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else//este else se ejecuta si el directorio donde se crean los respaldos existe.
{
if (inscripciones != null && inscripciones.Count > 0)//valida que la lista que llena el DataGridView tenga datos
{
if(!File.Exists(rutaFinal))//valida que el archivo no haya sido creado ya
{
crearExcel(dgv, inscripciones, rutaFinal);
}
}
else
{
MessageBox.Show("No hay datos para guardar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
And this is the code of the method that creates the excel, in case there is an error in this method that affects the other:
private void crearExcel(DataGridView dgv, IList<DTO_Inscripcion> inscripciones, string rutaFinal)
{
//try para capturar algun error que pueda suceder al momento de crear y dar formato al Excel
try
{
Microsoft.Office.Interop.Excel.Application aplicacion;
Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
aplicacion = new Microsoft.Office.Interop.Excel.Application();
libros_trabajo = aplicacion.Workbooks.Add();
hoja_trabajo =
(Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);
for (int i = 0; i < dgv.Rows.Count; i++)
{
for (int j = 0; j < dgv.Columns.Count; j++)
{
hoja_trabajo.Cells[i + 2, j + 1] = dgv.Rows[i].Cells[j].Value.ToString();
}
}
//nombre de las columnas del excel
hoja_trabajo.Cells[1, "A"] = "Nº Inscripcion";
hoja_trabajo.Cells[1, "B"] = "Orden";
hoja_trabajo.Cells[1, "C"] = "Socio";
hoja_trabajo.Cells[1, "D"] = "Nombre";
hoja_trabajo.Cells[1, "E"] = "Apellido";
hoja_trabajo.Cells[1, "F"] = "Vencimiento";
hoja_trabajo.Cells[1, "G"] = "Estado";
hoja_trabajo.Cells[1, "H"] = "Fecha Pago";
hoja_trabajo.Cells[1, "I"] = "Hora Ingreso";
hoja_trabajo.Cells[1, "J"] = "Hora Egreso";
//formato de la hoja
hoja_trabajo.Range["A1", "J" + (dgv.Rows.Count) + 1.ToString()].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
hoja_trabajo.Range["A1", "J1"].Font.Bold = true;
hoja_trabajo.Range["A1", "J1"].Font.Size = 16;
hoja_trabajo.Range["A1", "J1"].Interior.ColorIndex = 17;
hoja_trabajo.Range["A2", "J2" + (dgv.Rows.Count + 1).ToString()].Font.Size = 12;
hoja_trabajo.Columns.AutoFit();
//
//linea que guarda el archivo
libros_trabajo.SaveAs(rutaFinal, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
libros_trabajo.Close(true);
aplicacion.Quit();
MessageBox.Show("El respaldo se realizo correctamente", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Error al intentar generar el archivo Excel", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I have put a breakpoint to see what it returns File.Exists()
and it always returns false
, even if the file exists. I have forced it to enter true or false in the following ways:
if(!File.Exists(rutaFinal))//valida que el archivo no haya sido creado ya
{
crearExcel(dgv, inscripciones, rutaFinal);
}
and here taking out the !
if(File.Exists(rutaFinal))//valida que el archivo no haya sido creado ya
{
crearExcel(dgv, inscripciones, rutaFinal);
}
Both codes return false, which doesn't make sense. If you know of another way to validate that the file exists, I would appreciate it. I have read/write permissions.
I think I know your mistake... according to https://docs.microsoft.com/en-us/dotnet/api/system.io.file.exists?view=netcore-3.1 , your mistake might be that you don't have certain permissions , make sure you have read permissions before and run again
You could put the code with a little more order and not duplicate so much, something like this
Remember to define an extension for the file, it has to be
.xsl
or.xslx