Lock xml file writes through multiple aspx pages

  • Thread starter Thread starter vani
  • Start date Start date
V

vani

What is the best way to lock an xml file if there are multiple aspx pages
and/or ascx controls trying to write to it at the same time?
I already got a suggestion to use FileShare.None on a filestream that is
passed to XDocument, but I would prefer a solution that blocks/waits.
 
Are all of these reads under your control? If so then a mutex based on the
file name might be one way - so you only attempt to open the file if you can
get the mutex. But obviously this won't work unless you can do this on every
page and control which is trying to access the page.

Create a type to hide the file itself. Public properties and methods
can be added to allow interaction with the file's data. When access is
needed to the file and its data, create an object of the type. The
sample below likely provides a better explanation of what I mean.

regards
A.G.

public class FileContainer
{
private static Mutex mutex = new Mutex();
internal string pathAndFileName;
public FileContainer(string pathAndFileName)
{
this.pathAndFileName = pathAndFileName;
load();
}

private void load()
{
if (File.Exists(pathAndFileName))
{
mutex.WaitOne();
try
{
// read file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
}

private void save()
{
mutex.WaitOne();
try
{
// write file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
// additional methods, members & properties
...
}
 
Create a type to hide the file itself. Public properties and methods
can be added to allow interaction with the file's data. When access is
needed to the file and its data, create an object of the type. The
sample below likely provides a better explanation of what I mean.

regards
A.G.

public class FileContainer
{
private static Mutex mutex = new Mutex();
internal string pathAndFileName;
public FileContainer(string pathAndFileName)
{
this.pathAndFileName = pathAndFileName;
load();
}

private void load()
{
if (File.Exists(pathAndFileName))
{
mutex.WaitOne();
try
{
// read file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
}

private void save()
{
mutex.WaitOne();
try
{
// write file here
...
}
finally
{
mutex.ReleaseMutex();
}
}
// additional methods, members & properties
...
}

Thanks for the kick, will try.
 
Back
Top