0

I'm using c# to create a windows service that finds new zip files on a network drive and unzips them to a local directory. I'm using this Map Network Drive API to do the mapping. I first call the map function and if that fails I unmap the drive and attempt to remap the drive again. Errors:

  • mapDrive() "the local device name is already in use" , then try
  • unmapDrive() "This network connection does not exist"

private bool unmapDrive()
{
    try
    {
        NetworkDrive oNetDrive = new aejw.Network.NetworkDrive();
        oNetDrive.LocalDrive = driveLetter;
        oNetDrive.Force = true;
        oNetDrive.ShareName = @"\\IPADDRESS\LogFiles";
        oNetDrive.UnMapDrive();
        return true;
    }
    catch(Exception e)
    {
        Log(e.Message);
        return false;
    }
}

private bool mapDrive()
{
    try
    {
        NetworkDrive oNetDrive = new aejw.Network.NetworkDrive();
        oNetDrive.LocalDrive = driveLetter;
        //oNetDrive.SaveCredentials = true;
        oNetDrive.ShareName = @"\\IPADDRESS\LogFiles";
        oNetDrive.PromptForCredentials = true;
        oNetDrive.MapDrive();
        return true;
    }
    catch(Exception e)
    {
        Log(e.Message);
        return false;
    }
}

they are called like so

if (!mapDrive())
{
    unmapDrive();
    if (!mapDrive())
    {
        //if drive cannot be mapped, program will not work
        Log("Discoverer has failed to map drive, shutting down");
        this.Stop();

    }
}
Patrick
  • 1,717
  • 7
  • 21
  • 28
  • Do you actually need to map the drive? Anything that wants a path will accept the UNC path. – Alex K. Jun 11 '18 at 17:05
  • This occurs no matter what drive letter is used. I've also tried a "net use /delete *" – thecurdler Jun 11 '18 at 17:07
  • @AlexK I would go that route, but the service needs credentials that the user account does not have – thecurdler Jun 11 '18 at 17:10
  • WNetUseConnection can do that, E.g. https://stackoverflow.com/a/684040/246342 – Alex K. Jun 11 '18 at 17:12
  • Is the service running under a network account that has permissions to access the share? Also, I don't think you are allowed to use `PromptForCredentials` from a service on Vista or later. Services can't have GUI interactions any more. – NetMage Jun 11 '18 at 23:08
  • @AlexK Thank you WNetUseConnection is exactly what I needed – thecurdler Jun 13 '18 at 15:40
  • @NetMage thanks for the heads up, I'll use command line parameters for that – thecurdler Jun 13 '18 at 15:42

0 Answers0