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

落爺英雄遲暮 提交于 2020-01-13 16:30:34

问题


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

}

回答1:


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)


来源:https://stackoverflow.com/questions/28087927/why-file-copy-works-but-file-openread-prompts-access-denied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!