96

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

}

psubsee2003
  • 8,563
  • 8
  • 61
  • 79
shan
  • 1,311
  • 4
  • 13
  • 17

9 Answers9

147

You can simply call

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

It will create the file if it doesn't exist and open the file for appending.

Edit:

This is sufficient:

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

But if you insist on checking first, you can do something like this, but I don't see the point.

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

Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList, then unbox the object once and use the reference.

However, I perfer to use List<> for my collections:

public class EmployeeList : List<Employee>
Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
20

or:

using FileStream fileStream = File.Open(path, FileMode.Append);
using StreamWriter file = new StreamWriter(fileStream);
// ...
Dan
  • 7,286
  • 6
  • 49
  • 114
Mitja Bonca
  • 4,268
  • 5
  • 24
  • 30
  • 3
    For this case you would get an IOException because fileStream still locks the file when stream writer would like write to it. Instead pass the fileStream as argument to StreamWriter constructor. – salted Jan 20 '19 at 17:14
16

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

Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Andee
  • 753
  • 3
  • 12
7

2021

Just use File.AppendAllText, which creates the file if it does not exist:

File.AppendAllText("myFile.txt", "some text");
Jack
  • 871
  • 1
  • 9
  • 17
5

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

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
  • 3
    -1 Checking for file existence before opening the file is a wrong pattern. This introduces race conditions. See the other answers and [my comment on another question](https://stackoverflow.com/questions/9907682/create-a-txt-file-if-doesnt-exist-and-if-it-does-append-a-new-line#comment101632299_9907682). – ComFreek Aug 21 '19 at 08:25
1

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();
}
MartenCatcher
  • 2,713
  • 8
  • 26
  • 39
Eastop
  • 11
  • 1
  • 2
1

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))
            {...}
Abdul Hadee
  • 113
  • 6
0

For Example

    string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
        rootPath += "MTN";
        if (!(File.Exists(rootPath)))
        {
            File.CreateText(rootPath);
        }
Metin Atalay
  • 1,375
  • 18
  • 28
  • -1 Checking for file existence before opening the file is a wrong pattern. This introduces race conditions. See the other answers and [my comment on another question](https://stackoverflow.com/questions/9907682/create-a-txt-file-if-doesnt-exist-and-if-it-does-append-a-new-line#comment101632299_9907682). – ComFreek Aug 21 '19 at 08:25
  • My pattern like contains in linq. I mean it is normal. Sometimes files necessary authorization, opening the file should be the second solution instead of our answer. – Metin Atalay Aug 21 '19 at 11:47
  • @MetinAtalayI am sorry, I do not fully understand your comment. My concern is that if the file is created -- externally -- after `if (!(File.Exists(...)))`, but before `File.CreateText(...)`, then it is overwritten. – ComFreek Aug 21 '19 at 12:49
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;

}
Airn5475
  • 2,452
  • 29
  • 51
Deph
  • 11
  • Welcome to SO. Please provide more information why this code might answer the question. Furthermore provide a [mcve]. – Mathias Jan 31 '20 at 13:25