0

It is my first time to write code to function file operations. I need to compare old file with a new file. If the old file name is equal to a new file name, it needs to be overwritten (update). If not equal, creating a new file name. How to do this in a simple and best way?

public void FileCreateOrOverwritten(string file)
{
    try
    {
        if (File.Exists(file))
        {
            if (file == newFile)
            {
                //how to replace old file with a new one with new data (xml document)
                //need to use filestream
            }
            else
            {
                //how to create a new file with new data (xml document)
            }

        }
        .
        .
        .
    }
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
user1358072
  • 447
  • 2
  • 12
  • 26
  • [This](http://stackoverflow.com/a/2281769/706456) shall solve it for you. – oleksii Aug 01 '13 at 08:59
  • You mention xml - consider serialising like http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document or http://stackoverflow.com/questions/4220973/c-sharp-xml-serialization-deserialization – doctorlove Aug 01 '13 at 09:11

1 Answers1

0

To (over)write a file,

using (var writer = File.CreateText(file))
{
    for (...)
    {
        writer.WriteLine(...);
    }
}

You don't then need to decide if you have an old one to over-write or a new one to create. From the docs

"This method is equivalent to the StreamWriter(String, Boolean) constructor overload with the append parameter set to false. If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten"

If you are new to this, note the using

doctorlove
  • 18,872
  • 2
  • 46
  • 62
  • 1
    And the reason why `using` should be used, is that it guarantees that the `writer`'s Dispose method is called after the program exits the `using` block –  Aug 01 '13 at 09:08
  • well... i dont like this way. i think maybe it is better to remove the old file first then move the new file in if their file names are equal... – user1358072 Aug 01 '13 at 09:08
  • 1
    @user1358072 Do it however you want. The over-write in effect removes the old one for you, but if you'd rather do it yourself that's odd but it's your code – doctorlove Aug 01 '13 at 09:10