You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中将Local AppData文件复制到Temp目录?遇权限拒绝问题

问题描述

我正在开发一款需要调用Local AppData中文件的应用,打算将文件复制到Temp目录后进行编辑,但用C#执行复制操作时提示“Access denied(权限拒绝)”。已尝试修改app.manifest中的requestedExecutionLevel并关闭UAC,问题仍未解决。

相关代码

C# 复制方法

public void CopyChromeVersion()
{
    if (!File.Exists(Path.Combine(Path.GetTempPath(), $"{name}_lddata")))
    {
        File.Copy(file + "\\Last Version", tmpPath + "\\chrome_last_version");
    }
}

app.manifest 配置

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
    </application>
  </compatibility>
</assembly>

排查与解决思路

  • 修正路径拼接方式:
    手动拼接路径易出现分隔符错误或特殊字符解析问题,改用Path.Combine规范路径处理:

    public void CopyChromeVersion()
    {
        string destCheckPath = Path.Combine(Path.GetTempPath(), $"{name}_lddata");
        if (!File.Exists(destCheckPath))
        {
            string sourcePath = Path.Combine(file, "Last Version");
            string destPath = Path.Combine(tmpPath, "chrome_last_version");
            File.Copy(sourcePath, destPath);
        }
    }
    
  • 处理文件被占用的情况:
    Chrome的"Last Version"文件可能被Chrome进程锁定,无法直接复制。改用流复制并设置共享权限,允许读取被占用的文件:

    using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (FileStream destStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
    {
        sourceStream.CopyTo(destStream);
    }
    
  • 确认用户目录的正确性:
    管理员身份运行程序时,会访问管理员用户的Local AppData而非当前用户的。确保file变量指向当前用户的Local AppData目录:

    string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    // 替换为Chrome对应的子目录,例如Google\Chrome\User Data\...
    file = Path.Combine(localAppData, "Google", "Chrome", "目标子目录");
    
  • 验证Temp目录权限:
    确认tmpPath是通过Path.GetTempPath()获取的系统临时目录,避免自定义路径导致的权限异常。

内容的提问来源于stack exchange,提问作者XMPTXNXSS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 12:52:43