简体   繁体   中英

WPF C# StreamWriter does not write to file and raises no exception

I use this piece of code to write (append) text to a log file in my WPF app. The file's path is by default inside Program Files. If I run the app as normal user, the file is not written (or not created), but no permissions exception is raised, despite of the try-catch statement. If the user specifies a non-system folder for the log files (which can be done on runtime), everything works. If the app is run as admin, everything works even with the default (system) folder. This is clearly a permissions problem. I don't understand why this code doesn't raise an exception, if the user is non-admin and tries to create/write files inside a system folder. In such case, File.AppendText should raise UnauthorizedAccessException , shouldn't it? What is the problem here?

try
{
    using (StreamWriter w = File.AppendText(path))
    {
        w.WriteLine(line.ToString());
    }
}
catch (Exception ex)
{
    var message = $"{path}\n{ex.Message}";
    MessageBox.Show(message, "Log File Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

OS: Windows 10

Net Framework version 4

I use this piece of code to write (append) text to a log file in my WPF app. The file's path is by default inside Program Files. If I run the app as normal user, the file is not written (or not created), but no permissions exception is raised, despite of the try-catch statement.

You're hitting UAC virtualization .

AsRaymond Chen puts it :

UAC Virtualization kicks in for applications which were designed for versions of Windows prior to Windows Vista. These applications often assume that they are running with administrative privileges, and when they try to write to file or registry locations that are normally restricted to administrators, they expect them to succeed. So UAC Virtualization lets those writes succeed by secretly redirecting them to another location inside the user profile. The reverse happens when the application later tries to read the file or registry key: If the file or key exists in the redirected location, it is used instead of the one in the administrative location.

You can read the above-linked TechNet article for details . The short version is that you can find the files in the %LOCALAPPDATA%\VirtualStore directory and the keys under the HKEY_CURRENT_USER\Software\Classes\VirtualStore key.

Don't try and write to Program Files. Write to somewhere suitable in AppData instead, either ApplicationData or CommonApplicationData .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM