2016-06-09 38 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

相關問題