SHGetKnownFolderPath / Environment.GetFolderPath() returning wrong value for public documents

后端 未结 1 733
礼貌的吻别
礼貌的吻别 2021-01-12 00:24

I got a somewhat strange error when trying to resolve the CommonDocuments directory. It keeps resolving to the wrong directory, after the CommonDocuments direc

1条回答
  •  孤城傲影
    2021-01-12 01:11

    tl;dr: Behaviour is by design and only appears when you're running an assembly that was compiled for x86 CPUs on a x64 OS


    Longer version:
    Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) accesses the 32-bit hive of the Windows Registry.
    The actual path to the folder is stored in the 64-bit hive. The issue has been forwarded to the Windows team and may be fixed in a future version of Windows.

    For a bit more information see the Microsoft connect report


    Workaround create a console application with the following code and compile it for ANY CPU

    static void Main(string[] args)
    {
            Console.WriteLine("{0}", Environment.GetFolderPath(System.Environment.SpecialFolder.CommonDocuments));
    }
    

    then call it from your main application:

    Process proc = new Process();
    ProcessStartInfo info = new ProcessStartInfo("myConsoleApp.exe");
    
    // allow output to be read
    info.RedirectStandardOutput = true;
    info.RedirectStandardError = true;
    info.UseShellExecute = false;
    proc.StartInfo = info;
    
    proc.Start(); 
    proc.WaitForExit();
    string path = proc.StandardOutput.ReadToEnd();
    

    this will launch the ANY CPU executable, which only prints out the desired path to the standard output. The output then is read in the main application and you get the real path.

    0 讨论(0)
提交回复
热议问题