4

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

}
Ali Yousefi
  • 2,355
  • 2
  • 32
  • 47
  • Is the filestream closed after a previous attempt which resulted in exception ? – Venugopal M Jan 22 '15 at 11:47
  • 1
    Your code doesn't actually show `File.OpenRead` being used. Although checking, the constructor you are using *seems* to default to adding `FileShare.Read` anyway, which is what `File.OpenRead` uses... – Marc Gravell Jan 22 '15 at 11:56
  • 1
    Perhaps it's caused by `File.OpenRead` using `FileShare.Read` and not `FileShare.ReadWrite`. I'd expect the former to fail if another process has already opened the file for writing. Try `new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)` – CodesInChaos Jan 22 '15 at 12:12
  • It's definitely the `new FileStream()` that throws, is it? (And not `new StreamDecryption(...)`) – Matthew Watson Jan 22 '15 at 12:17
  • thanks @CodesInChaos this is worked for me and no show access error: using (var fileStream = new System.IO.FileStream(@"filepath", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite)) – Ali Yousefi Jan 22 '15 at 12:40

1 Answers1

7

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)
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262