对新创建的文件的UnauthorizedAccessException

Jer*_*rry 10 c# file-access

我有一个应用程序正在查看旧数据的一些文件.为了确保我们不破坏好项目,我将文件复制到临时位置.我正在检查的一些目录是源代码目录,它们有.svn文件夹.我们使用Subversion来管理我们的代码.

一旦我搜索了所有文件,我想删除临时缓存.听起来很简单吧?

出于某种原因,我的所有.svn目录都不会从缓存中删除.他们崩溃了应用程序.

由于原因(太深入了这里),我必须使用临时文件夹,因此出于政治原因,"扫描原始文件"是不可能的.

我可以进入资源管理器并删除它们.没问题.没有警告.只是删除.但代码崩溃,"访问{file}被拒绝".我对这个问题的态度很有帮助,所以任何帮助都会受到赞赏.

虽然我为了你的理智而将函数简化为LITTLE,但代码REALLY就是这么简单.

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);
}
Run Code Online (Sandbox Code Playgroud)

    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.
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n B 12

据我所知,Subversion将其.svn子目录中的文件标记为只读.

尝试在删除文件之前重置只读属性.我真的不知道任何C#,但快速谷歌建议这可能会有所作为:

File.SetAttributes(file, FileAttributes.Normal);
Run Code Online (Sandbox Code Playgroud)