We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:
This code snippet shows a technique for getting exclusive access to a file (read in this case):
// Try to open a file exclusively
FileInfo fi = new FileInfo(fullFilePath);
int attempts = maxAttempts;
do
{
try
{
// Try to open for reading with exclusive access...
fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
// Ignore any errors...
catch { }
if (fs != null)
{
break;
}
else
{
Thread.Sleep(100);
}
}
while (--attempts > 0);
// Did we manage to open file exclusively?
if (fs != null)
{
// use open file....
}