Dante1986
Dante1986

Reputation: 59969

File is not created after another has been created

I am trying to create 2 XML files in the same folder. For some reason it does create the first one, but does not create the second one.

Could it be that the first one is still being created when an attempt to create the second file is made, and therefore the latter fails?

I don't get any errors with the code:

if (File.Exists(FileNameTextBox.Text + ".AA.xml"))
{
    MessageBox.Show("Already exists. renaming to *.old" + Environment.NewLine +
                    "if there is already an *.old file, this will be deleted.");
    if (File.Exists(FileNameTextBox.Text + ".AA.xml.old"))
    {
        File.Delete(FileNameTextBox.Text + ".AA.xml.old");
    }
    File.Move(FileNameTextBox.Text + ".AA.xml", FileNameTextBox.Text + ".AA.xml.old");
}
if (!File.Exists(FileNameTextBox.Text + ".AA.xml"))
{
    XmlTextWriter textWritter = new XmlTextWriter(FileNameTextBox.Text + ".AA.xml", null);
    textWritter.WriteStartDocument();
    textWritter.WriteStartElement("Data");
    textWritter.WriteEndElement();
    textWritter.Close();
}

if (File.Exists("BB.xml"))
{
    if (File.Exists("BB.xml.old"))
    {
        File.Delete("BB.xml.old");
    }
    File.Move("BB.xml", "BB.xml.old");
}
if (!File.Exists("BB.xml"))
{
    XmlTextWriter textWritterPC3 = new XmlTextWriter("BB.xml", null);
    textWritterPC3.WriteStartDocument();
    textWritterPC3.WriteStartElement("Data");
    textWritterPC3.WriteEndElement();
    textWritterPC3.Close();
}

Upvotes: 0

Views: 101

Answers (3)

Jonas W
Jonas W

Reputation: 3260

The comment is only making the last if case execute the first row.. The last if should look like this. I don't know if it's only in your example. Your example

if (!File.Exists("BB.xml")) //            {
            XmlTextWriter textWritterPC3 = new XmlTextWriter("BB.xml", null);

should be

if (!File.Exists("BB.xml")) //            
{
    XmlTextWriter textWritterPC3 = new XmlTextWriter("BB.xml", null);
    textWritterPC3.WriteStartDocument();
    textWritterPC3.WriteStartElement("Data");

    textWritterPC3.WriteEndElement();
    textWritterPC3.Close();
}

Upvotes: 0

Polyfun
Polyfun

Reputation: 9639

You are not specifying an absolute path for your file names, so you are using whatever the current directory happens to be, which is not reliable. Also you may need to call DirectoryInfo.Refresh() or FileInfo.Refresh() to make sure you are seeing the latest directory information (whether the file exists or not).

Upvotes: 1

Grhm
Grhm

Reputation: 6854

Whats in FileNameTextBox.Text? Does it specify a directory path?

Your second file is created without saying which directory. So it will be created in the current directory - which is not necessarily the directory specified by FileNameTextBox.Text

Upvotes: 3

Related Questions