简体   繁体   中英

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

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", ConfigWindow.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM