[c#] Create File If File Does Not Exist

I need to get my code to read if file doesnt exist create else append. Right now it is reading if it does exist create and append. Here is the code:

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

Would I do this?

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

Edit:

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();
}

}

This question is related to c# streamwriter

The answer is


This works as well for me

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();
}

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;

}

You don't even need to do the check manually, File.Open does it for you. 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


This will enable appending to file using StreamWriter

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

This is default mode, not append to file and create a new file.

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

Anyhow if you want to check if the file exists and then do other things,you can use

using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
            {...}

or:

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

For Example

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

Yes, you need to negate File.Exists(path) if you want to check if the file doesn't exist.