为什么File.copy工作,但File.OpenRead提示访问被拒绝? [英] why File.copy works but File.OpenRead prompts access denied?

查看:1805
本文介绍了为什么File.copy工作,但File.OpenRead提示访问被拒绝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要复制它正在被另一个进程使用加密文件



本作品:

  System.IO.File.Copy(路径1,路径2,真正的); 



但下面的代码无法正常工作。提示文件访问被拒绝错误:

 使用(的FileStream FILESTREAM =新的FileStream(文件名,FileMode.Open,FileAccess.Read) )//访问被拒绝使用打开文件
{
(流copyFileStream =新StreamDecryption(新的FileStream(将copyTo,FileMode.Create)))
{

$} b $ b}

我怎样才能复制加密的文件,如果文件是由另一个进程使用?



感谢



更新:我用这个代码,并为我工作:

使用

 (VAR FILESTREAM =新System.IO.FileStream(@文件路径,System.IO.FileMode.Open,System.IO。 FileAccess.Read,System.IO.FileShare.ReadWrite))
{

}


< DIV CLASS =h2_lin>解决方案

如果您使用 FileShare.Read ,其中隐含发生在你的榜样,打开文件会失败,如果另一个进程已经打开了书面文件。

  File.OpenRead(文件名)
新的FileStream(文件名,的FileMode。开放,FileAccess.Read)
新的FileStream(文件名,FileMode.Open,FileAccess.Read,FileShare.Read)

如果您指定 FileShare.ReadWrite ,这不会触发开幕错误,但其他进程可能会发生变化,而你读你读数据它。您的代码应该能够处理不完全数据写入或这样的变化。

 新的FileStream(文件名,FileMode.Open,FileAccess.Read ,FileShare.ReadWrite)


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

}

解决方案

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)

这篇关于为什么File.copy工作,但File.OpenRead提示访问被拒绝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆