Search code examples
.netvb.netxmlwriter

VB.NET: XMLWriter() check if directory exists and if file exists, otherwise create them


I am running into a small bug in a vb.net console application I am working with right now.

It contains this piece of code:

writer = XmlWriter.Create(xmlSaveLocation, settings)

The value of xmlSaveLocation is: C:\temp\crawl\uncompressed\fullCrawl.xml

I ran into the bug because this is the first time I run the application and neither the directories, nor the file exist on my local C: drive.

I would like to find out how can I add a check for the directories and file before the assignment to the writer variable occurs, that way future users don't have to run into this problem.

My first and only attempt was to add this If statement below:

If (Not System.IO.Directory.Exists(xmlSaveLocation)) Then
    System.IO.Directory.CreateDirectory(xmlSaveLocation)
    writer = XmlWriter.Create(xmlSaveLocation, settings)
Else
    writer = XmlWriter.Create(xmlSaveLocation, settings)
End If

That only works for the directory, but it breaks on the file.

Any help would be much appreciated.

Thank you.


Solution

  • This should work for you:

    ' Exctract the directory path
    Dim xmlSaveDir=System.IO.Path.GetDirectoryName(xmlSaveLocation)
    
    ' Create directory if it doesn't exit
    If (Not System.IO.Directory.Exists(xmlSaveDir)) Then
        System.IO.Directory.CreateDirectory(xmlSaveDir)
    End If
    
    ' now, use a file stream for the XmlWriter, this will create or overwrite the file if it exists
    Using fs As New FileStream(xmlSaveLocation, FileMode.OpenOrCreate, FileAccess.Write)
        Using writer As XmlWriter = XmlWriter.Create(fs)
            ' use the writer...
            ' and, when ready, flush and close the XmlWriter
            writer.Flush()
            writer.Close()
        End Using
        ' flush and close the file stream
        fs.Flush()
        fs.Close()
    End Using