相关疑难解决方法(0)

使用Directory.Delete()和Directory.CreateDirectory()覆盖文件夹

在我的WebApiaction方法中,我想使用以下代码创建/覆盖一个文件夹:

string myDir = "...";
if(Directory.Exists(myDir)) 
{
    Directory.Delete(myDir, true);
}
Directory.CreateDirectory(myDir);

// 1 - Check the dir 
Debug.WriteLine("Double check if the Dir is created: " + Directory.Exists(myDir));

// Some other stuff here...

// 2 - Check the dir again
Debug.WriteLine("Check again if the Dir still exists: " + Directory.Exists(myDir));
Run Code Online (Sandbox Code Playgroud)

问题

奇怪的是,有时在创建目录后,该目录不存在!

有时第一次检查目录时(数字1的位置); 其他时候Directory.Exist()返回.第二次检查目录时(数字2的位置)也是如此.truefalse

笔记

  • 这部分代码都没有抛出任何异常.
  • 只有在服务器上发布网站时才能重现这一点.(Windows server 2008)
  • 访问同一文件夹时发生.

问题

  • 这是并发问题竞争条件吗?
  • 不是WebApi或操作系统处理并发?
  • 这是覆盖文件夹的正确方法吗?
  • 当我们对同一个文件有很多API请求时,我是否应该手动锁定文件?

或者一般情况:

  • 这种奇怪行为的原因是什么?

更新:

  • 使用DirectoryInfoRefresh(),而不是 …

c# asp.net-web-api asp.net-web-api2

10
推荐指数
1
解决办法
4171
查看次数

如何使用C#同步和一致地删除NTFS上的文件夹

这个:

Directory.Delete(dir, true);
Run Code Online (Sandbox Code Playgroud)

不是同步的.

在紧接着的行中,您仍然可以操作/读取目录.

例如,这个:

Directory.Delete(destinationDir, true);
Directory.CreateDirectory(destinationDir);
Thread.Sleep(1000);
Run Code Online (Sandbox Code Playgroud)

导致文件夹不存在.删除运行异步,CreateDirectory不创建,因为它已经存在,然后删除实际触发并删除目录.

是否有一个IO API可以提供一致性?

涉及的答案Thread.Sleep将援引Zalgo.我想要一个真正的解决方案.

c# io ntfs

5
推荐指数
1
解决办法
924
查看次数

标签 统计

c# ×2

asp.net-web-api ×1

asp.net-web-api2 ×1

io ×1

ntfs ×1