1

Hello This is the code i am trying : If the file existes , append to that file else create a new one . I need to write data line by line

                    FileExists = File.Exists(NewFileName);
                    if (FileExists = false)
                    {
                        using (fs =new FileStream(NewFileName, FileMode.Create))
                        {
                            sw = new StreamWriter(fs);
                            MessageBox.Show(Record);
                            sw.WriteLine(Record);
                            fs.Close();
                        }
                    }
                    else
                    {
                        using (fd = new FileStream(NewFileName, FileMode.Append))
                        {
                            sw = new StreamWriter(fd);
                            MessageBox.Show(Record);
                            sw.WriteLine(Record,true);
                        }
                    }

                }
user2668901
  • 47
  • 1
  • 1
  • 5

1 Answers1

1

This is because your code never enters the FileExists = false branch: it is an assignment, not a comparison.

You can add an extra = to make it a comparison (i.e. make it FileExists == false) but the idiomatic way of checking the opposite of a condition is with the unary operator !.

Change the condition as follows to make it work:

if (!FileExists)
    ...

In addition, you forgot to close or flush your StreamWriter.

You can unify both branches by using the ternary operator, like this:

using (fs =new FileStream(NewFileName, FileExists ? FileMode.Append : FileMode.Create)) {
    sw = new StreamWriter(fs);
    MessageBox.Show(Record);
    sw.WriteLine(Record);
    sw.Close(); // <<== Add this line
    fs.Close();
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks !! But No use checked that too – user2668901 Aug 09 '13 at 18:48
  • Yes i have tried showing the record and it does have a value and the file location is the same . have tried the append and write options for the file . i am not able to find where am i going wrong . It may be with the file mode or file access – user2668901 Aug 09 '13 at 19:00
  • @user2668901 You'd get an exception if there were a problem with file permissions. Check my last edit - you forgot to close the stream writer. – Sergey Kalinichenko Aug 09 '13 at 19:01