2012-04-30 24 views
37

Necesito obtener mi código para leer si el archivo no existe create else append. Ahora mismo está leyendo si existe crear y anexar. Aquí está el código:Crear archivo si no existe el archivo

if (File.Exists(path)) 
{ 
    using (StreamWriter sw = File.CreateText(path)) 
    { 

¿Lo haría?

if (! File.Exists(path)) 
{ 
    using (StreamWriter sw = File.CreateText(path)) 
    { 

Editar:

string path = txtFilePath.Text; 

if (!File.Exists(path)) 
{ 
    using (StreamWriter sw = File.CreateText(path)) 
    { 
     foreach (var line in employeeList.Items) 
     { 
      sw.WriteLine(((Employee)line).FirstName); 
      sw.WriteLine(((Employee)line).LastName); 
      sw.WriteLine(((Employee)line).JobTitle); 
     } 
    } 
} 
else 
{ 
    StreamWriter sw = File.AppendText(path); 

    foreach (var line in employeeList.Items) 
    { 
     sw.WriteLine(((Employee)line).FirstName); 
     sw.WriteLine(((Employee)line).LastName); 
     sw.WriteLine(((Employee)line).JobTitle); 
    } 
    sw.Close(); 
} 

}

+1

[File.AppendAllText] (http: // MSDN .microsoft.com/es-us/library/ms143356.aspx): esto está haciendo exactamente lo que necesita en una sola línea de código. –

+0

@ShadowWizard Since th se etiqueta la tarea OP puede ser dirigida para mostrar la lógica condicional. – Yuck

+4

@Yuck - ¿deberes para reinventar la rueda? ¡Yuck! ;) –

Respuesta

63

sólo tiene que llamar

using (StreamWriter w = File.AppendText("log.txt")) 

Se va a crear el archivo si no existe y abrir el archivo para anexar.

Editar:

Esto es suficiente:

string path = txtFilePath.Text;    
using(StreamWriter sw = File.AppendText(path)) 
{ 
    foreach (var line in employeeList.Items)     
    {      
    Employee e = (Employee)line; // unbox once 
    sw.WriteLine(e.FirstName);      
    sw.WriteLine(e.LastName);      
    sw.WriteLine(e.JobTitle); 
    }     
}  

Pero si insiste en comprobar en primer lugar, se puede hacer algo como esto, pero no veo el punto.

string path = txtFilePath.Text;    


using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))     
{      
    foreach (var line in employeeList.Items)      
    {       
     sw.WriteLine(((Employee)line).FirstName);       
     sw.WriteLine(((Employee)line).LastName);       
     sw.WriteLine(((Employee)line).JobTitle);      
    }     
} 

Además, una cosa a destacar con su código es que usted está haciendo un montón de unboxing innecesaria. Si tiene que usar una colección simple (no genérica) como ArrayList, entonces desempaquete el objeto una vez y use la referencia.

Sin embargo, preferimos utilizar List<> para mis colecciones:

public class EmployeeList : List<Employee> 
6

Sí, tiene que negar File.Exists(path) si desea comprobar si el archivo no se existe.

12

o:

using(var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 
{ 
    using (StreamWriter sw = new StreamWriter(path, true)) 
    { 
     //... 
    } 
} 
-1

Para el Ejemplo

string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)); 
     rootPath += "MTN"; 
     if (!(File.Exists(rootPath))) 
     { 
      File.CreateText(rootPath); 
     } 
Cuestiones relacionadas