2016-06-09 56 views
0

我正在运行在我正在使用的vb.net控制台应用程序中的一个小错误。VB.NET:XMLWriter()检查目录是否存在,如果文件存在,否则创建它们

它包含这一段代码:

writer = XmlWriter.Create(xmlSaveLocation, settings) 

xmlSaveLocation的值是:C:\ TEMP \抓取\未压缩\ fullCrawl.xml

我跑进错误,因为这是第一我运行该应用程序,并且目录和文件都不存在于本地C:驱动器上。

我想知道如何在赋值给writer变量之前添加对目录和文件的检查,这样未来的用户不必遇到这个问题。

我的第一个也是唯一的尝试是添加下面这个if语句:

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 

这仅适用于该目录,但是它破坏的文件。

任何帮助将不胜感激。

谢谢。

回答

1

这应该为你工作:

' 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 
+0

感谢您的帮助,但不幸的是,当我用你的代码,我得到一个异常:访问路径“C:\ TEMP \爬\未压缩的\ fullCrawl。 xml'被拒绝。当我到达xmlwriter部分的文件流时。谢谢。 –

+0

我认为这是因为部分:System.IO.Directory.CreateDirectory(xmlSaveLocation)创建:fullCrawl.xml作为目录而不是文件,而filestreamer试图打开该目录,就像它是一个文件。你知道一个解决方法,而不必将文件名作为单独的字符串片段添加吗?谢谢。 –

+0

是的,你是对的:) 我更新了代码,现在它应该正确地创建目录。 – nasskov

相关问题