【发布时间】: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