How to synchronize file writing

Asked

Viewed 24 times

1

Hello, I am developing a classic ASP application and I need to write a JSON to a data.json file. Problem is that several users may request the recording in this file, I would like to know what is the best solution for this problem? I wanted you to avoid the error that two users request to write to the file at the same time. I know it is difficult to occur but it is not impossible. So there would be some way to synchronize the writing avoiding that multiple users order the writing at the same time making one at a time placing them in a queue?

Here’s the code:

dim filesys, filetxt

Dim path,pastalocal
pastalocal = split(Request.ServerVariables("script_name"),"/")
path = Server.MapPath("/"&pastalocal(1))

Const ForReading = 1, ForWriting = 2, ForAppending = 8


Dim lineData
Set fso = Server.CreateObject("Scripting.FileSystemObject") 
set fs = fso.OpenTextFile(path&"\data2.json", ForReading, true) 
Do Until fs.AtEndOfStream 
    lineData = fs.ReadLine      
Loop 

fs.close: set fs = nothing

Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.OpenTextFile(path&"\data2.json", ForWriting, True)
If lineData = "" Then
    filetxt.Write(Request.Form("dataJson"))
Else
    filetxt.Write(lineData&","&Request.Form("dataJson"))
End If
filetxt.Close 
  • Present the code of how you are opening the file for writing

  • Already includes the code @Leandroangelo

1 answer

0

Hello,

From the moment you make this code:

Set filetxt = filesys.OpenTextFile(path&"\data2.json", ForWriting, True)

any other attempt to make another opening for writing to the file will give error, in order to open again for writing you have to do

filetxt.Close 

if you put something like this :

on error goto erroAbertura
Set filetxt = filesys.OpenTextFile(path&"\data2.json", ForWriting, True)

So I guess that solves your problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.