Kathy Judd
Kathy Judd

Reputation: 737

Can't use System.IO.File.Copy() to copy file to Volume Id

I have a C# WinForm app using .Net Framework 4.5.2. I'm grabbing a list of Volume Ids and so I can copy a file to the root folder.

  ManagementObjectSearcher ms = new ManagementObjectSearcher("Select * from Win32_Volume");    
foreach(ManagementObject mo in ms.Get())   
{
    var guid = mo["DeviceID"].ToString();
}

Then I grab the Volume Id and call System.IO.File.Copy() to copy

System.IO.File.Copy( "a.pdf", System.IO.Path.Combine( @"\\?\Volume{c06fa891-c5a9-11e7-9bc6-f01faf0be092}\", "a.pdf" ) );

But get "Illegal characters in path."

      at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
   at System.Security.Permissions.FileIOPermission.QuickDemand(FileIOPermissionAccess access, String fullPath, Boolean checkForDuplicates, Boolean needFullPath)
   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
   at System.IO.File.Copy(String sourceFileName, String destFileName)
   at ThumbDrives.Form1.button1_Click(Object sender, EventArgs e) in Form1.cs:line 46

I know it's not a permission issue and I can use "copy" in command prompt to copy the file to Volume Id. Is it possible to copy files using .Net Framework to copy files using Volume Id instead of the drive letter?

Thanks

Upvotes: 1

Views: 466

Answers (1)

TyCobb
TyCobb

Reputation: 9089

Looking at the Microsoft's Reference Source for EmulateFileIOPermissionChecks, you should be able to get this to work if you disable UseLegacyPathHandling as noted by AppContextSwitchOverrides page.

internal static void EmulateFileIOPermissionChecks(string fullPath)
{
    //...
    if (AppContextSwitches.UseLegacyPathHandling || !PathInternal.IsDevice(fullPath))
    {
        if (PathInternal.HasWildCardCharacters(fullPath))
        {
            throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
        }

        //...
    }
}

Example Config:

<configuration>  
    <runtime>
        <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false" /> 
    </runtime> 
</configuration> 

Upvotes: 1

Related Questions