Crear archivo si el archivo no existe


76

Necesito que mi código se lea si el archivo no existe, crear más agregar. Ahora mismo está leyendo si existe crear y adjuntar. Aquí está el código:

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

¿Haría esto?

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 : esto está haciendo exactamente lo que necesita en una sola línea de código ..
— Shadow Wizard está vacunando

@ShadowWizard Dado que esto está etiquetado como tarea, OP puede en realidad ser dirigido para mostrar la lógica condicional.
— Yuck

5
@Yuck - ¿tarea para reinventar la rueda? ¡Qué asco! ;)
— Shadow Wizard va a vacunar el

Respuestas:


113

Simplemente puedes llamar

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

Creará el archivo si no existe y lo abrirá para agregarlo.

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 verificar primero, puede hacer algo como esto, pero no veo el sentido.

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 para señalar con su código es que está haciendo mucho unboxing innecesario. Si tienes que usar una colección simple (no genérica) como ArrayList, desempaqueta el objeto una vez y usa la referencia.

Sin embargo, prefiero usar List<>para mis colecciones:

public class EmployeeList : List<Employee>

18

o:

using FileStream fileStream = File.Open(path, FileMode.Append);
using StreamWriter file = new StreamWriter(fileStream);
// ...

1
En este caso, obtendría una IOException porque fileStream aún bloquea el archivo cuando el escritor de secuencias desea escribir en él. En su lugar, pase fileStream como argumento al constructor StreamWriter.
— salado el



0

Por ejemplo

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

-1 Verificar la existencia del archivo antes de abrirlo es un patrón incorrecto. Esto introduce condiciones de carrera. Vea las otras respuestas y mi comentario sobre otra pregunta .
— ComFreek

Mi patrón como contiene en linq. Quiero decir que es normal. A veces los archivos necesitan autorización, abrir el archivo debería ser la segunda solución en lugar de nuestra respuesta.
— Metin Atalay

@MetinAtalay Lo siento, no entiendo completamente tu comentario. Mi preocupación es que si el archivo se crea, externamente, después if (!(File.Exists(...))), pero antes File.CreateText(...), se sobrescribe.
— ComFreek

0
private List<Url> AddURLToFile(Urls urls, Url url)
{
    string filePath = @"D:\test\file.json";
    urls.UrlList.Add(url);

    //if (!System.IO.File.Exists(filePath))
    //    using (System.IO.File.Delete(filePath));

    System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(urls.UrlList));

    //using (StreamWriter sw = (System.IO.File.Exists(filePath)) ? System.IO.File.AppendText(filePath) : System.IO.File.CreateText(filePath))
    //{
    //    sw.WriteLine(JsonConvert.SerializeObject(urls.UrlList));
    //}
    return urls.UrlList;
}

private List<Url> ReadURLToFile()
{
    //  string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"App_Data\file.json");
    string filePath = @"D:\test\file.json";

    List<Url> result = new List<Url>(); ;
    if (!System.IO.File.Exists(filePath))
        using (System.IO.File.CreateText(filePath)) ;



    using (StreamReader file = new StreamReader(filePath))
    {
        result = JsonConvert.DeserializeObject<List<Url>>(file.ReadToEnd());
        file.Close();
    }
    if (result == null)
        result = new List<Url>();

    return result;

}

Bienvenido a SO. Proporcione más información sobre por qué este código podría responder a la pregunta. Además, proporcione un ejemplo mínimo reproducible .
— Mathias

0

Esto funciona bien para mi

string path = TextFile + ".txt";

if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
{
    File.Create(HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
{
    w.WriteLine("{0}", "Hello World");
    w.Flush();
    w.Close();
}

0

Esto permitirá agregar al archivo usando StreamWriter

 using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}

Este es el modo predeterminado, no agregar al archivo y crear un nuevo archivo.

using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
                           or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}

De todos modos, si desea verificar si el archivo existe y luego hacer otras cosas, puede usar

using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
            {...}
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.