【发布时间】:2010-01-05 16:18:48
【问题描述】:
我有一个应用程序正在查看一些文件以查找旧数据。为了确保我们不会破坏好的项目,我将文件复制到一个临时位置。我正在检查的一些目录是源代码目录,它们有 .svn 文件夹。我们使用 Subversion 来管理我们的代码。
搜索完所有文件后,我想删除临时缓存。听起来很简单,对吧?
由于某种原因,我的所有 .svn 目录都不会从缓存中删除。他们使应用程序崩溃。
由于某些原因(此处太深,无法深入),我必须使用临时文件夹,因此出于政治原因,仅“扫描原始文件”是不可能的。
我可以进入资源管理器并删除它们。没问题。没有警告。只是删除。但代码因“访问 {file} 被拒绝”而崩溃。我对此一无所知,因此将不胜感激。
虽然为了您的理智,我已经稍微简化了函数,但代码真的就是这么简单。
List<string> tmpCacheManifest = new List<string>();
string oldRootPath = "C:\\some\\known\\directory\\";
string tempPath = "C:\\temp\\cache\\";
foreach (string file in ListOfFilesToScan)
{
string newFile = file.Replace(oldRootPath, tempPath);
// This works just fine.
File.Copy(file, newFile);
tmpCacheManifest.add(newFile);
}
// ... do some stuff to the cache to verify what I need.
// Okay.. I'm done.. Delete the cache.
foreach (string file in tmpCacheManifest)
{
// CRASH!
File.Delete(file);
}
* 更新 *:异常是 UnauthorizedAccessException。文本是“访问路径 'C:\temp\cache\some-sub-dirs\.svn\entries' 被拒绝。”
它发生在 XP、XP-Pro 和 Windows 7 下。
* 更新 2 * 我的验证都没有尝试查看颠覆文件。不过,我确实需要它们。这是政治废话的一部分。我必须证明每个文件都被复制了......无论它是否被扫描。
我意识到 File.Delete 的常见嫌疑人是什么。我意识到 UnauthorizedAccessException 是什么意思。我没有访问权限。这是不费吹灰之力的。但我只是复制了文件。我如何不访问该文件?
* 更新 3 * 答案在“只读”标志中。这是我用来修复它的代码:
foreach (string file in ListOfFilesToScan)
{
string newFile = file.Replace(oldRootPath, tempPath);
// This works just fine.
File.Copy(file, newFile);
//// NEW CODE ////
// Clear any "Read-Only" flags
FileInfo fi3 = new FileInfo(fn);
if ((fi3.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
fi3.Attributes = (FileAttributes)(Convert.ToInt32(fi3.Attributes) - Convert.ToInt32(FileAttributes.ReadOnly));
}
tmpCacheManifest.add(newFile);
}
// ... do some stuff to the cache to verify what I need.
【问题讨论】:
-
有什么例外?可能存在文件锁定。
-
File.Delete 可以抛出至少七种不同的异常类型。你要的是哪一个?
-
@Roboto,你不是说:WTE吗? TCBAFL?
-
“对缓存做一些事情”是否保留了任何文件,而不是正确关闭它们?
-
乔恩,你也删除了一些文字,这是想要的吗?
标签: c# file-access