无法使用System.IO.File.Copy()将文件复制到Volume Id

时间:2018-03-06 20:31:24

标签: c# .net winforms

我有一个使用.Net Framework 4.5.2的C#WinForm应用程序。我抓取了卷ID列表,因此我可以将文件复制到根文件夹。

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

然后我抓住Volume Id并调用System.IO.File.Copy()来复制

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

但是获得"路径中的非法字符。"

      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

我知道这不是许可问题,我可以使用" copy"在命令提示符下将文件复制到卷标识。是否可以使用.Net Framework复制文件以使用Volume Id而不是驱动器号复制文件?

由于

1 个答案:

答案 0 :(得分:1)

查看Microsoft EmulateFileIOPermissionChecks的Microsoft参考源,如果您按AppContextSwitchOverrides页所述禁用UseLegacyPathHandling,则应该可以使其生效。

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

        //...
    }
}

示例配置:

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