Search code examples
c#network-programmingshared-directory

How to check Network/Shared Folder stability?


At work we have a shared folder where I do some data collection. From my computer I have to make sure, that the server is not down during data collection.

So, my approach would be, in an interval of few minutes I will connect and reconnect to my server a several times (if it fails, then stop data collection and wait or do next task)

What is the best way to connect and reconnect to a network drive/shared folder? I would do something like

public bool checkNet(UNCPath)
{
int connected = 0;
bool unstable = true;
while(unstable)
{
SubfunctionConnect(UNCPath); //connect to network using cmd 'net use' command
if(directory.exists(UNCPath) 
{
++connected;
}
else
{
connected = 0;
}
}
if(connected >= 3) unstable = false; //after 3 in arrow  successful connections then leave loop and proceed further tasks
return true;
}

Solution

  • I'm maintaining a project which has a similar feature to your requirement.

    In that feature, we use FileSystemWatcher to monitor all kinds of operation of specific UNC location. You can implement the OnError event which will be triggered while the UNC path is not available.

    You can check the link above for detail, still, a short sample here

    using (FileSystemWatcher watcher = new FileSystemWatcher(@"\\your unc path"))
    {
        // Watch for changes in LastAccess and LastWrite times, and
        // the renaming of files or directories.
        watcher.NotifyFilter = NotifyFilters.LastAccess
                             | NotifyFilters.LastWrite
                             | NotifyFilters.FileName
                             | NotifyFilters.DirectoryName;
    
        // Only watch text files.
        watcher.Filter = "*.txt";
    
        watcher.Created += (s, e) => { Console.WriteLine($"Created {e.Name}"); };
        watcher.Deleted += (s, e) => { Console.WriteLine($"Deleted {e.Name}"); };
        watcher.Error += (s, e) => { Console.WriteLine($"Error {e.GetException()}"); };
    
    
        // Begin watching.
        watcher.EnableRaisingEvents = true;
    
        // Wait for the user to quit the program.
        Console.WriteLine("Press 'q' to quit the sample.");
        while (Console.Read() != 'q') ;
    }