Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Updated Code:

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

}

                

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading