7

Using .NET / C#, how to determine if a network path (e.g. \mymachine\myfolder) is available or not (online or offline)? Is there a way to be notified by WMI of such event?

Thanks!

Martin
  • 39,309
  • 62
  • 192
  • 278

3 Answers3

6

You can use Directory.Exists to check if a path exists.

bool folderExists = Directory.Exists(@"\\Path\To\Folder");
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
  • If the network is offline, I believe this will return false, versus the network online, but the path just doesn't exist. – Brain2000 May 07 '20 at 21:30
2

Maybe try the Ping class:

http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx

It will tell you if a host is available, but I don't know if it will tell you whether a particular share/path is available.

NeilMonday
  • 2,680
  • 2
  • 25
  • 29
1

Just try to use it. It will cause an error condition if it isn't. You have to code against that condition anyway: why do it twice?

user207421
  • 305,947
  • 44
  • 307
  • 483
  • This is costly. I would prefer the OS to notify me. – Martin Oct 27 '10 at 16:00
  • 3
    That doesn't mean anything. It's more costly to test the same condition twice, and to code the same recovery twice. I'm assuming you're going to use the resource some time. Pre-testing its availability is essentially invalid: you are introducing a timing window during which it can become unavailable after you tested it. Basically you are asking the computer to predict the future. – user207421 Oct 28 '10 at 06:04
  • Just using it, in some situations, causes things like Directory.GetFiles(), and OpenFileDialog.ShowDialog() to appear to hang for a couple of minutes (one way I can make this happen is to access the share, disconnect the VPN, then access the share again). – Les Oct 28 '16 at 00:06