【问题标题】:How to copy a file in using a string that has %UserProfile% in C#如何在 C# 中使用具有 %UserProfile% 的字符串复制文件
【发布时间】:2012-05-16 07:34:42
【问题描述】:

我正在尝试使用它来复制文件 -

 private void button1_Click(object sender, EventArgs e)
    {
        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        if (File.Exists(@"C:\Users\%UserProfile%\AppData\Roaming\.minecraft\bin\minecraft.jar"))
            try
            {                  
                File.Copy(@"C:\Users\%UserProfile%\AppData\Roaming\.minecraft\bin\minecraft.jar", @"C:\Users\%UserProfile%\Documents\MinecraftBackup\minecraft.jar", true);
            }

除非我将 %UserProfile% 更改为我的实际用户名,否则它将无法正常工作,我该如何解决这个问题?

【问题讨论】:

    标签: c# copy profile user-profile


    【解决方案1】:

    代替:

    C:\Users\%UserProfile%\AppData\Roaming\.minecraft\bin\minecraft.jar
    

    试试

    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                 @".minecraft\bin\minecraft.jar")
    

    实际上,任何时候看到“C:\Users\%UserProfile%\AppData\Roaming\”,都应该使用“Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)”。

    【讨论】:

      【解决方案2】:

      %userprofile% 变量包括完整路径,一直到驱动器的根目录。

      C:\Windows\System32>echo %userprofile%
      C:\Users\[myusername]
      

      【讨论】:

      • 这将在其他人的计算机上使用,所以我不相信它会起作用
      【解决方案3】:
      var s = @"C:\Users\%UserProfile%\AppData\Roaming\";
      var s2 = Environment.ExpandEnvironmentVariables(s);
      

      s2有扩展数据

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        • 2012-05-18
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 2019-06-20
        相关资源
        最近更新 更多