我正在使用Dropbox中的文件在服务器之间进行通信。过了一会儿,我意识到在Dropbox内的文件上执行时,每隔一段时间基本File
操作就会出现延迟。
我需要的是这样的事情:
public class MyFile
{
const int maxWaitCount = 60;
//..
/// <summary>
/// remove file - also has to work inside Dropbox directory
/// </summary>
/// <returns>0 for ok or error code</returns>
public int rm()
{
string name = Os.winInternal(FullName);
if (File.Exists(name))
{
File.Delete(name);
#region double check if file is gone
if (Ensure)
return awaitFileVanishing(name);
#endregion
}
return 0;
}
//..
private int awaitFileMaterializing(string fileName) //..
private int awaitFileVanishing(string fileName) //..
/// <summary>
/// Constructor: auto-ensure mode for file systems that do not synchronously wait for the end of an IO operation i.e. Dropbox
/// </summary>
/// <remarks>only use the ensure mode if it has to be guaranteed that the IO operation was completely done
/// when the method call returns; necessary e.g. for Dropbox directories since (currently) Dropbox first updates the
/// file in the invisible . folder and then asynchronously updates the visible file and all the remote copies of it</remarks>
/// <param name="filename"></param>
public MyFile(string filename)
{
Ensure = filename.ToLower().Contains("dropbox");
// ..
}
}
由于我需要一个快速的解决方案,我想出了一个我正在回答我自己的问题的答案。但是,我很容易想象你们中的一些人也有这个问题,并找到了一个不同的,可能更具说服力的解决方案。请告诉我。
答案 0 :(得分:0)
这是awaitFileMaterializing
和awaitFileVanishing
的当前解决方案,用作MyFile
的一部分。
private int awaitFileMaterializing(string fileName)
{
int count = 0;
bool exists = false;
while (count < maxWaitCount)
{
try
{
exists = File.Exists(fileName);
}
catch (Exception) { } // device not ready exception if Win 2003
if (exists)
break;
Thread.Sleep(5);
count++;
}
if (count >= maxWaitCount)
throw new FileNotFoundException("ensure failed - timeout.", fileName);
return -count;
}
private int awaitFileVanishing(string fileName)
{
int count = 0;
bool exists = true;
while (count < maxWaitCount)
{
try
{
exists = File.Exists(fileName);
}
catch (Exception) { } // device not ready exception if Win 2003
if (!exists)
break;
Thread.Sleep(5);
count++;
}
if (count >= maxWaitCount)
throw new IOException("ensure failed - timeout in deleting " + fileName + ".");
return -count;
}
答案 1 :(得分:0)
您可以创建FileSystemWatcher
来监控您的Dropbox文件夹。 FileSystemWatcher有一个已删除的事件,您可以附加到该事件,告诉您何时从正在监视的文件夹中删除文件。