Hi to all,
I am new in this forum. I was searching help about a recent problem i have got with filestream object.
Specifically I have the need that two or more users read and write a file content and so I coded these lines of code:
. . .
. . . this code is in a function.. for simplicity I reported a snippet
public enum dbLockType { _none =0, _lock, _unLock, _default}
long lockPos = -1;
long lockRec = -1;
int blockSize = 100;
FileStream DtFile = new FileStream(@"\\server\d\folder\test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite,8000);
. . .
. . .
public bool getBufferFromDisk(long RecordNumber, byte[] toArray, int startingAt, int length, dbLockType dbLock)
{
long seekPosition = GetFilePos(RecordNumber); // calc RecordNumber*blockSize
try {
DtFile .Seek(seekPosition, System.IO.SeekOrigin.Begin);
DtFile .Read(toArray, startingAt, length);
if ( dbLock == dbLockType._lock) {
if ( lockPos > -1)
DtFile .Unlock(lockPos, blockSize); // unlock previous locks
DtFile .Lock(seekPosition, blockSize);
lockPos = seekPosition;
lockRec = RecordNumber;
}
}
catch(IOException e) {
return false;
}
return true;
}
After that the first user open the file and call the getBufferFromDisk with these parms:
getBufferFromDisk( 8, toArray, 0, 100, dbLock);
in this way it lock the filestream at pos (7 x100) for 100 bytes.
the second user try to open the file and to execute the same function with these parms:
getBufferFromDisk( 0, toArray, 0, 100, dbLock);
at this point I got an error telling me that the file is partially locked by other process.
I found the prorblem occur at this line :
DtFile .Read(toArray, startingAt, length);
Stange , because I have locked 100 bytes starting from pos 700 not at 0.
After some reading I found this article that seems more like my problem : http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic15633.aspx
So I tried to go further and after some investigation I found :
1. Even though I change the FileAccess to .Read ( while the first pgm is locking the region) the second user find the record at pos 0 locked.
2. the lock is extended to the whole buffer , that is 8K.
3. all this is true if the second user try to open and read something in this buffer if something in this buffer is locked, otherwise all is ok!, I mean if the first user lock something at pos 8500 , 100 the second user has no problem at all.
What is this , a bug? Am I wrong in something ? this is the correct way to lock-unlock regions ?.
Could someone help me to get rid of this problem ?
Thanks to all ?
JossGP