写入文件时,如何正确解析对路径的访问被拒绝?

时间:2015-10-02 22:23:40

标签: vb.net file streamwriter

这是我的代码:

Dim htmlFile = "\\folder\test.htm"
If File.Exists(htmlFile) Then
    File.Delete(htmlFile)
End If
Using strWriter As StreamWriter = New StreamWriter(htmlFile, False)
    strWriter.Write("content")
End Using

它大部分时间都可以使用,但偶尔我会得到一个例外,即访问路径' \ folder \ test.htm'被拒绝。"此行发生异常:

Using strWriter As StreamWriter = New StreamWriter(fileName, False)

如何确保始终创建新文件并且永远不会导致异常?

1 个答案:

答案 0 :(得分:-1)

如果两台服务器写入同一文件时出现错误,此例程会等待一段时间:

Retry_IT:

try
      Dim htmlFile = "\\folder\test.htm"
      If File.Exists(htmlFile) Then
         File.Delete(htmlFile)
      End If
      Using strWriter As StreamWriter = New StreamWriter(htmlFile, False)
         strWriter.Write("content")
      End Using
Catch Exception
      Thread.sleep(2000)   '2 seconds
      Goto Retry_It
End Try