Reputation: 2765
I want to copy an encrypted file which is being used by another process.
This works:
System.IO.File.Copy("path1", "path2",true);
but the below code is not working. Prompts "file access denied" error:
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))//access denied open file
{
using (Stream copyFileStream = new StreamDecryption(new FileStream(copyTo, FileMode.Create)))
{
}
}
How can i copy an encrypted file if file is used by another process?
Thanks
Update:i used this code and worked for me:
using (var fileStream = new System.IO.FileStream(@"filepath", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
}
Upvotes: 4
Views: 6572
Reputation: 108880
If you use FileShare.Read
, which happens implicitly in your example, opening the file will fail if another process has already opened the file for writing.
File.OpenRead(fileName)
new FileStream(fileName, FileMode.Open, FileAccess.Read)
new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)
If you specify FileShare.ReadWrite
, this will not trigger an error on opening, but the other process might change the data you're reading while you read it. Your code should be able to handle incompletely written data or such changes.
new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Upvotes: 7