首页 > 解决方案 > C# WPF 应用程序发布后不写入文件

问题描述

首先,论坛给了我很好的想法和解决方案,只是通过阅读。

对于我目前的情况,我不会真正寻找它。

我编写了一个在调试和发布模式下完美运行的 WPF 应用程序。但是,一旦我发布您,就没有更多了。

我尝试了不同的发布方式。

该应用程序由 CD、DVD 或记忆棒提供。clickonce方法曾经使用过,有时不会。

它应该被创建为独立的可执行文件。并且包括框架。

我的问题是,通过发布版本发布后,我无权写入 Environment.CurrentDirectory 或外部的文件。

在一种情况下,提供了受影响的文件但无法更改。只要我在安装后交换文件,我就可以更改它。

在另一种情况下,我无法使用该指令创建文件。使用 StreamWriter。但也无法使用 System.IO 创建文件夹。

该应用程序由管理员运行。只有当应用程序使用 RunAsAdmin 执行时,它才能正常运行。

该文件是一个 txt 文件,用作日志文件。但是,没有管理员权限的用户也应该能够在必要时更新日志文件。

无论用户权限如何,我该怎么做才能使我的应用程序通常可以生成文件?

非常感谢。

标签: c#wpfpermissionspublishstreamwriter

解决方案


您可以查看我的代码片段:

private bool HasPathAccessable(string path)
{
    DirectorySecurity sec = Directory.GetAccessControl(path);
    WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
    foreach (FileSystemAccessRule acr in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
    {
        //Console.WriteLine("{0} | {1} | {2} | {3} | {4}", acr.IdentityReference.Value, acr.FileSystemRights, acr.InheritanceFlags, acr.PropagationFlags, acr.AccessControlType);
        if (acr.IdentityReference.Value == currentIdentity.Name)
        {
            if (acr.FileSystemRights == FileSystemRights.FullControl && acr.AccessControlType == AccessControlType.Allow)
            {
                Console.WriteLine($"{currentIdentity.Name} accessable to {path}");
                return true;
            }
        }
    }
    Console.WriteLine($"{currentIdentity.Name} inaccessable to {path}");
    return false;
}

private void ChangePathAccessControlCurrentUser(string path, bool isFile)
{
    WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();

    if (isFile)
    {
        var pathAccessControl = File.GetAccessControl(path);
        pathAccessControl.AddAccessRule(new FileSystemAccessRule(currentIdentity.Name, FileSystemRights.FullControl, AccessControlType.Allow));
        File.SetAccessControl(path, pathAccessControl);
        Console.WriteLine($"AddAccessRule File : {path}");
    }
    else
    {
        var pathAccessControl = Directory.GetAccessControl(path);
        pathAccessControl.AddAccessRule(new FileSystemAccessRule(currentIdentity.Name, FileSystemRights.FullControl, AccessControlType.Allow));
        Directory.SetAccessControl(path, pathAccessControl);
        Console.WriteLine($"AddAccessRule Directory : {path}");
    }
}

推荐阅读