【问题标题】:why File.copy works but File.OpenRead prompts access denied?为什么 File.copy 有效但 File.OpenRead 提示访问被拒绝?
【发布时间】:2015-01-22 11:40:24
【问题描述】:

我想复制一个正在被另一个进程使用的加密文件。

这行得通:

System.IO.File.Copy("path1", "path2",true);

但下面的代码不起作用。提示“文件访问被拒绝”错误:

using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))//access denied open file
{
    using (Stream copyFileStream = new StreamDecryption(new FileStream(copyTo, FileMode.Create)))
    {

    }
}

如果文件被另一个进程使用,我如何复制加密文件?

谢谢

更新:我使用了这段代码并为我工作:

using (var fileStream = new System.IO.FileStream(@"filepath", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{

}

【问题讨论】:

  • 文件流是否在上次尝试导致异常后关闭?
  • 您的代码实际上并未显示正在使用的File.OpenRead。尽管进行了检查,但您使用的构造函数 似乎 无论如何都默认添加 FileShare.Read,这就是 File.OpenRead 使用的...
  • 可能是由File.OpenRead 使用FileShare.Read 而不是FileShare.ReadWrite 引起的。如果另一个进程已经打开文件进行写入,我希望前者会失败。试试new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  • 肯定是new FileStream() 抛出的,是吗? (而不是new StreamDecryption(...)
  • 感谢@CodesInChaos 这对我有用并且没有显示访问错误:使用(var fileStream = new System.IO.FileStream(@"filepath", System.IO.FileMode.Open, System.IO .FileAccess.Read, System.IO.FileShare.ReadWrite))

标签: c# encryption copy


【解决方案1】:

如果您使用FileShare.Read,这在您的示例中隐式发生,如果另一个进程已经打开文件进行写入,则打开文件将失败。

File.OpenRead(fileName)
new FileStream(fileName, FileMode.Open, FileAccess.Read)
new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)

如果您指定FileShare.ReadWrite,这不会在打开时触发错误,但其他进程可能会在您读取时更改您正在读取的数据。您的代码应该能够处理不完整写入的数据或此类更改。

new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 2018-03-10
    • 1970-01-01
    • 2018-04-28
    • 2012-02-07
    • 1970-01-01
    • 2014-05-18
    • 2023-03-24
    相关资源
    最近更新 更多