Crear Archivo Si El Archivo No Existe
Necesito que mi código se lea si el archivo no existe create else append. En este momento está leyendo si existe crear y anexar. 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();
}
}
5 answers
Simplemente puede llamar a
using (StreamWriter w = File.AppendText("log.txt"))
Creará el archivo si no existe y abrirá el archivo para anexarlo.
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 insistes en comprobar primero, puedes 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 señalar con su código es que está haciendo un montón de unboxing innecesario. Si tiene que usar una colección simple (no genérica) como ArrayList
, entonces descomprima el objeto una vez y usa la referencia.
Sin embargo, prefiero usar List<>
para mis colecciones:
public class EmployeeList : List<Employee>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-30 15:43:12
O:
using(var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(path, true))
{
//...
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-30 11:44:09
Ni siquiera es necesario hacer la comprobación manualmente, Archivo.Open lo hace por ti. Try:
using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append)))
{
Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 10:30:55
Sí, necesita negar File.Exists(path)
si desea verificar si el archivo no existe.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-30 11:40:22
Por Ejemplo
string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
rootPath += "MTN";
if (!(File.Exists(rootPath)))
{
File.CreateText(rootPath);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-25 07:25:20