¿cómo puedo verificar si un archivo está vacío en C#?¿Está vacío el archivo de verificación
necesita algo así como:
if (file is empty)
{
//do stuff
}
else
{
//do other stuff
}
¿cómo puedo verificar si un archivo está vacío en C#?¿Está vacío el archivo de verificación
necesita algo así como:
if (file is empty)
{
//do stuff
}
else
{
//do other stuff
}
Uso FileInfo.Length:
if(new FileInfo("file").Length == 0)
{
// empty
}
comprobar la propiedad Exists para averiguar, si el archivo existe en absoluto.
if (!File.Exists(FILE_NAME))
{
Console.WriteLine("{0} does not exist.", FILE_NAME);
return;
}
else
{
if (new FileInfo(FILE_NAME).Length == 0)
{
Console.WriteLine("{0} is empty", FILE_NAME);
return;
}
}
El problema aquí es que el sistema de archivos es volátil. Considere:
if (new FileInfo(name).Length > 0)
{ //another process or the user changes or even deletes the file right here
// More code that assumes and existing, empty file
}
else
{
}
Esto puede ocurrir y sucede. En general, la forma en que necesita manejar escenarios de archivo-io es volver a pensar el proceso para usar bloques de excepciones, y luego poner su tiempo de desarrollo en escribir buenos manejadores de excepciones.
//You can use this function, if your file exists as content, and is always copied to your debug/release directory.
/// <summary>
/// Include a '/' before your filename, and ensure you include the file extension, ex. "/myFile.txt"
/// </summary>
/// <param name="filename"></param>
/// <returns>True if it is empty, false if it is not empty</returns>
private Boolean CheckIfFileIsEmpty(string filename)
{
var fileToTest = new FileInfo(Environment.CurrentDirectory + filename);
return fileToTest.Length == 0;
}
Así es como he resuelto el problema. Verificará si el archivo existe primero y luego verificará la longitud. Considero que un archivo inexistente está efectivamente vacío.
var info = new FileInfo(filename);
if ((!info.Exists) || info.Length == 0)
{
// file is empty or non-existant
}
Además de responder de @tanascius, puede utilizar
try
{
if (new FileInfo("your.file").Length == 0)
{
//Write into file, i guess
}
}
catch (FileNotFoundException e)
{
//Do anything with exception
}
Y lo hará sólo si el archivo existe, en la sentencia catch puede crear archivos y Agin ejecutar código.
No debe hacer algo como eso en su declaración catch. – UrbanEsc
He descubierto que comprobar el campo FileInfo.Length no siempre funciona para ciertos archivos. Por ejemplo, y el archivo .pkgdef vacío tiene una longitud de 3. Por lo tanto, tuve que leer realmente todos los contenidos del archivo y devolver si eso era igual a una cadena vacía.
Me encontré con esta respuesta al revisar publicaciones. Bienvenido, esta es la primera publicación buena. Lo mejoraría añadiendo un enlace a alguna documentación u otro recurso que explique por qué tu respuesta es una buena solución –
¿Qué pasa si el archivo contiene espacio? FileInfo("file").Length
es igual a 2.
Pero creo que el archivo también está vacío (no tiene ningún contenido excepto espacios (o saltos de línea)).
He usado algo como esto, pero ¿alguien tiene una mejor idea?
Puede ayudar a alguien.
string file = "file.csv";
var fi = new FileInfo(file);
if (fi.Length == 0 ||
(fi.Length < 100000
&& !File.ReadAllLines(file)
.Where(l => !String.IsNullOrEmpty(l.Trim())).Any()))
{
//empty file
}
En lugar de 'IEnumerable.ToList(). Count == 0' puedes usar'! IEnumerable.Any() ' . Evite leer toda la lista. –
sí, claro, gracias @ JérémieBertrand –
Probado. Eso es exactamente lo que quiero. calificado y marcado. Gracias – Arcadian
nota: 'new FileInfo (" file ") .Length' lanzará una' FileNotFoundException' si el archivo no existe, por lo que si hay un caso de que el archivo no existe, asegúrese de marcar la propiedad 'Existe' antes de verificar 'Longitud'. –
Gran ayuda. ¡Gracias! – snapper