开发者

check if network drive exists with timeout in c#

i created a windows service that move files around between the server's hard drive (where the service is installed) to the network drive mapped in the server. one of the problems I encountered while creating a solution was network problems.

how do i check if a network drive exists while setting a timeout in checking it? If it times out, I catch the exception and retry in X number of minute开发者_StackOverflows and leave items in queue.

thanks!


Put the call in a seperate thread and close the thread after a certain timeout. The following link implements a timeout logic for a method:

http://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time/

EDIT

One of the comments on the topic above suggest a better implementation using .NET Async Pattern:

public static T SafeLimex<T>(Func<T> F, int Timeout, out bool Completed)   
   {
       var iar = F.BeginInvoke(null, new object());
       if (iar.AsyncWaitHandle.WaitOne(Timeout))
       {
           Completed = true;
           return F.EndInvoke(iar);
       }
         F.EndInvoke(iar);
         Completed = false;
       return default(T);
   } 


As far as I recall, using the normal System.IO methods do the trick. So in this case, you'd simply use:

if (Directory.Exists("Z:\\MyNetworkFolder"))
{
    // Gogogo
}
else
{
    Thread.Sleep(MyTimeout);
}

If the folder does not exist, pause for whatever timeout you choose. This should do the job perfectly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜