开发者

How to avoid file is being used by another process in vb.net

开发者 https://www.devze.com 2023-03-08 23:02 出处:网络
I am trying to check whether file exists or not. if not create and write something into it. The file is getting created but not updating and getting error message says it is being used by another proc

I am trying to check whether file exists or not. if not create and write something into it. The file is getting created but not updating and getting error message says it is being used by another process

Code snippet:

Public shared sub MyXml()
  If Not System.IO.File.Exists("configfile.xml") Then
    Dim writer As New System.Xml.XmlTextWriter(fullPath.ToString + "\configfile.xml", Nothing)
  End If

  Dim xmlElement As New XElement("FilePath", ConfigW开发者_如何学编程indow.Datapath.Text)
  System.IO.File.WriteAllText(fullPath + "\configfile.xml", xmlElement.ToString())
end sub()

Any suggestions please...


WriteAllText will create the file, so you can simply remove the If statement:

Public Shared Sub MyXml()
  Dim xmlElement As New XElement("FilePath", ConfigWindow.Datapath.Text)
  System.IO.File.WriteAllText(fullPath + "\configfile.xml", xmlElement.ToString())
End Sub

The reason the file is locked is that your code creates an XmlTextWriter that is not disposed, so it keeps holding on to the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消