Search code examples
vb.netstreamjson.net

How Could Disconnect From Local JSON File?


I need to download every 10 minute a JSON file in to my project. (Older file delete and new file replace it) and between delete and replace last process read data from data with newtonsoft.json library, so far so good.

Now my problem: after read data from JSON file, delete old data cancel and say file used by other program and cant replace it new JSON file

Dim Sreader As StreamReader = File.OpenText("C:\Common\Current.json")
Dim Reader As JsonTextReader = New JsonTextReader(Sreader)
Dim Treader As JObject = CType(JToken.ReadFrom(Reader), JObject)


S1 = Treader.SelectToken("current.temp_c").ToString()

Solution

  • Using Sreader As StreamReader = File.OpenText("C:\Common\Current.json")
    Using Reader As New JsonTextReader(Sreader)
        Dim Treader As JObject = CType(JToken.ReadFrom(Reader), JObject)
        S1 = Treader.SelectToken("current.temp_c").ToString()
        '...
    End Using
    End Using
    File.Delete("C:\Common\Current.json")
    

    Separate from this, as an extra precaution it's easy to rename the file to include the current date and time prior to opening it. This will at least protect against a locked file issue from blocking additional updates.

    Dim filePath As String = "C:\Common\Current.json"
    Dim tempPath As String = $"C:\Common\Current-{DateTime.Now:yyyyMMddHHmmss}.json"
    
    File.Move(filePath, tempPath)
    Using Sreader As StreamReader = File.OpenText(tempPath)
    Using Reader As New JsonTextReader(Sreader)
        Dim Treader As JObject = CType(JToken.ReadFrom(Reader), JObject)
        S1 = Treader.SelectToken("current.temp_c").ToString()
        '...
    End Using
    End Using
    File.Delete(tempPath)