【问题标题】:C# WPF Application don't write a file after publishingC# WPF 应用程序发布后不写入文件
【发布时间】:2021-11-11 04:28:30
【问题描述】:

首先,论坛给了我很好的想法和解决方案。

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

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

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

应用程序由 CD、DVD 或记忆棒提供。 clickonce方法用过一次有时不会。

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

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

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

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

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

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

我该怎么做才能让我的应用程序通常可以生成文件,而不管用户权限如何?

非常感谢。

【问题讨论】:

  • 父文件夹有哪些安全参数?它允许用户编辑文件夹的内容还是只允许管理员? (右击->属性->安全选项卡)
  • 程序无法写入程序文件目录。如果您的程序安装在那里,您将遇到您描述的问题。通过写入 appdata 目录来解决。
  • 父文件夹为应该使用该应用程序的所有用户共享。管理员还拥有发布和完全访问权限。 - 该应用程序没有安装在像程序文件(x64/x84)这样的特殊文件夹中,而是安装在我的安装项目中。由于我已将特殊文件夹程序文件 (x84) 设置为占位符路径。

标签: c# wpf permissions publish streamwriter


【解决方案1】:

你可以查看我的代码sn-p:

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}");
    }
}

【讨论】:

  • 谢谢 Benny,您的代码看起来不错。我试一试,给你答案。
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2014-05-31
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多