Implementing virtual drive with Dokan. Stuck on WriteFile
Question
I'm writing my filesystem using C# and Dokan library and got stuck on WriteFile.
public int WriteFile(
String filename,
Byte[] buffer,
ref uint writtenBytes,
long offset,
DokanFileInfo info)
{
try
{
FileStream fs = File.OpenWrite( GetFullPath(filename) , FileMode.Open );
fs.Seek(offset, SeekOrigin.Begin);
fs.Lock(offset, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
fs.Unlock(offset, buffer.Length);
writtenBytes = (uint)buffer.Length;
return 0;
}
catch (Exception e)
{
Console.WriteLine("FAIL WriteFile {0}", e.Message);
return -1;
}
}
When I run app and open txt file from Dokan's virtual drive, add some line and try to save it. I get error from notepad "The parameter is incorect".
In code I get exception on File.OpenWrite() call. The exception is System.IO.IOException. Message: "The process cannot access the file foo.txt because it is being used by another process."
- File is opened only by notepad.
- Same behavior can be observed with Mirror example delivered with Dokan library
- I added admin permissions to my program in the manifest, it didn't help
Dokan is supposed to work as proxy, allowing to call WriteFile defined by user, right? How can I do this if it's locked for writing?
Please help. Maybe you have any experience with Dokan or any clue why it's not working.
I'm using - Win 7 Pro x64 - 64 bit Dokan driver - App is compiled as x86
Solution
You must call Dispose on stream before leaving the method. That's not the best solution. You shuld construct file stream in CreateFile , pass it to info.Context and the use it in ReadFile , WriteFile and call dispose on it in Cleanup.