0

I'm writing a part of a program that shall copy a batch of files from the current computer to a defined list of computers. If these computers are not available, the code will hang for a long time trying to access them. Is there any functionallity in C# to check if the machine is available and then skip if it's not?

MFWs = File.ReadAllLines(GuiManager.MyConfigManagerConfig.MachinesList);
        foreach (string MFW in MFWs)
        {
          if (MFW != System.Environment.MachineName)
          {
            String target = @"\\" + MFW + @"\D\IbSi\config\" + Path.GetFileName(ConfigFile);
            String backup = @"\\" + MFW + @"\D\IbSi\userdata\" + Path.GetFileName(ConfigFile);
            try
            {
              File.Copy(source, target, true);
              File.Copy(source, backup, true);
            }
            catch (Exception ex)
            {
              Manager.SendMessage("Failed to copy " + Path.GetFileName(ConfigFile) + " to " + MFW + "\n" + ex.Message);
            }
          }
        }
Jamie Babineau
  • 746
  • 2
  • 12
  • 25
lewi
  • 477
  • 1
  • 5
  • 18
  • 3
    You're always dealing with "it could be available when you make the request to see if it's available, but not when you actually need it."; so your best bet is to try the operation. There are certain things you can do; make sure the DNS entries are up to date on the local computer; maybe that will reduce the time resolution takes. Looks like this Stack Overflow question deals with just that; by using threads (or a Task) to do certain tasks (like file copy) and timing out if it takes too long: http://stackoverflow.com/questions/1232953/speed-up-file-exists-for-non-existing-network-shares – George Stocker Jun 15 '16 at 13:28

1 Answers1

1

You could ping the computer before starting the copy (taken from this answer):

using System.Net.NetworkInformation;

public static bool IsHostAvailable(string nameOrAddress)
{
    bool pingable = false;
    Ping pinger = new Ping();
    try
    {
        PingReply reply = pinger.Send(nameOrAddress);
        pingable = reply.Status == IPStatus.Success;
    }
    catch (PingException)
    {
        // Discard PingExceptions and return false;
    }
    return pingable;
}

As noted in the comments you need to make sure the firewall on the servers is open for pings (ICMP echo requests)

Community
  • 1
  • 1
mhu
  • 17,720
  • 10
  • 62
  • 93
  • 1
    Note, if the remote computer has been configured to block pings, then this routine will always return false even when the computer is available. – sgmoore Jun 15 '16 at 13:57