Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why File.copy works but File.OpenRead prompts access denied?

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))
{

}
like image 925
Ali Yousefi Avatar asked Oct 27 '25 02:10

Ali Yousefi


1 Answers

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)
like image 174
CodesInChaos Avatar answered Oct 29 '25 16:10

CodesInChaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!