Search code examples
c#network-programmingunc

Unable to delete file from UNC path


I wanted to have an application remove a targeted file from specified worksations. The user executing the software would be an admin on the target machine so I used the following code for a test:

string strTarget = @"\\" + textBox1.Text + @"\C$\Temp\temp.txt";

            try
            {
                File.Delete(strTarget);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failure to delete: " + ex.Message);
            }

I then created a \Temp\Temp.txt file on both my own workstation and another test machine. I am an admin on both machines and can manually access and delete the file through the UNC path in question. When I ran the code debugger no exceptions are thrown, but the file doesn't delete. I can't figure our what is not happening for this to fail.

Is there anything I can check or any code I need to add? I've done a search on other questions, but I havn't been able to find an answer yet.


Solution

  • If you're running under Vista/7, your program is probably running under non-escalated priveleges. Make sure you either explicitly run your program as an administrator, or specify it in your project's manifest file:

      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!--
          UAC Manifest Options
          If you want to change the Windows User Account Control level replace the 
          requestedExecutionLevel node with one of the following.
    
        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />
    
         If you want to utilize File and Registry Virtualization for backward 
         compatibility then delete the requestedExecutionLevel node.
    -->
        <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
      </requestedPrivileges>