VB.NET: XMLWriter() 检查目录是否存在和文件是否存在,否则创建它们
VB.NET: XMLWriter() check if directory exists and if file exists, otherwise create them
我 运行正在处理我正在使用的 vb.net 控制台应用程序中的一个小错误。
包含这段代码:
writer = XmlWriter.Create(xmlSaveLocation, settings)
xmlSaveLocation 的值为:C:\temp\crawl\uncompressed\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
这只适用于目录,但它会破坏文件。
如有任何帮助,我们将不胜感激。
谢谢。
这应该适合你:
' 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
我 运行正在处理我正在使用的 vb.net 控制台应用程序中的一个小错误。
包含这段代码:
writer = XmlWriter.Create(xmlSaveLocation, settings)
xmlSaveLocation 的值为:C:\temp\crawl\uncompressed\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
这只适用于目录,但它会破坏文件。
如有任何帮助,我们将不胜感激。
谢谢。
这应该适合你:
' 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