Search code examples
c#filestream

How can i create a new file using FileStream without overwriting existing?


I am creating an xml file using the following:

string filename = string.Format("MyXMLFile{0}-{1}", Id, Name);
try
{
    FileStream fs = new FileStream(filename + ".xml", FileMode.Create);
    using (XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding()))
    {
       //write xml data here
    }
}
catch (exception ex)
{

}

The issue is that this code is called from else where in a for loop and the filename could be the same name in some situations. Is there a way I can tell the FileStream that if the filename exists , dont overwrite but create a new one ?

for example if the filename is TestXmlFile.xml then next round create TestXmlFile(1).xml and the next is TestXmlFile(2).xml


Solution

  • From MSDN:

    FileMode.Create

    Specifies that the operating system should create a new file. If the file already exists, it will be overwritten

    So, i would check first if file exists using

    File.Exists(FILE_PATH)

    and use a counter or a Timestamp(i believe this is approach is much better) to create the new one.