【问题标题】:C# An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dllC# 在 mscorlib.dll 中发生“System.UnauthorizedAccessException”类型的未处理异常
【发布时间】:2016-12-05 19:33:30
【问题描述】:

大家早上好,

我已经为应用程序创建了设置向导,当我运行应用程序时,我可以看到来自已安装文件夹中的 txt 文件的数据,但是当我尝试在 txt 文件中编辑数据时出现错误

在 mscorlib.dll 中出现“System.UnauthorizedAccessException”类型的未处理异常 附加信息:拒绝访问路径“C:\Program Files (x86)\Jean-Paul Sartre Variety Theatre\CustomerStorage.txt”。

string text = "";
StreamWriter sw = new StreamWriter("CustomerStorage.txt");  //THAT LINE GENERATE ERROR  

foreach (var item in Customers)
{
    text = item.Value.CustomerName + "*" + item.Value.CustomerEmail + "*" + (int)item.Value.Customertype + "*" + item.Value.BookDate + "*" + item.Value.CustomerNo + "*" + item.Value.BookedPlayName + "*" + item.Value.PaymentStatus + "*" + item.Value.SeatNoOne + "*" + item.Value.SeatNoTwo + "*" + item.Value.SeatNoThree + "*" + item.Value.SeatNoFour + "*" + item.Value.SeatNoFive + "*" + item.Value.SeatNoSix + "*" + item.Value.PriceToPay + "*" + item.Value.GetPlayNo + "*" + item.Value.TotalNumberOfSeatsCustomer + "*";
    if (item.Value.Customertype == CustomerType.GoldMember)
    {
        GoldMember gm = (GoldMember)item.Value;
        //saving gold member with new created date
        gm.CreatedDate = gm.CreatedDate;
        text += gm.CreatedDate + "*";
    }
    sw.WriteLine(text);
}
sw.Close();

我不知道我在创建设置向导时是否犯了任何错误,我应该在将 txt 文件添加到文件系统文件夹时获得类似权限。

【问题讨论】:

  • 您的应用程序是否以管理员权限运行?默认情况下,UAC 会阻止在没有管理员权限的情况下运行的应用程序写入 Program Files 文件夹及其子文件夹。如果 CustomerStorage 是可编辑文件,最好将其存储在本地应用程序数据文件夹 (c:\Users\\AppData\Local) 的某个位置
  • 你检查过你的应用有写权限吗?
  • 还重构您的代码以将您的 StreamWriter 对象包装在 using() {} 代码块构造周围,以处理/利用对象的自动处置..

标签: c# wpf installation


【解决方案1】:

授权访问方法解决了这个问题,谢谢大家。

public bool GrantAccess(string fullPath)
    {
        DirectoryInfo dInfo = new DirectoryInfo(fullPath);
        DirectorySecurity dSecurity = dInfo.GetAccessControl();
        dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
        dInfo.SetAccessControl(dSecurity);
        return true;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多