【问题标题】:System.UnauthorizedAccessException when trying to open a StreamWriter with a previously opened file [duplicate]尝试使用以前打开的文件打开 StreamWriter 时出现 System.UnauthorizedAccessException [重复]
【发布时间】:2019-04-16 14:23:42
【问题描述】:

我正在尝试在读取隐藏文件后写入它/使用默认值。尝试重新打开 StreamWriter 后,我收到 UnauthorizedAccessException,告诉我对该文件的访问被拒绝,但其中没有任何有用的信息(至少我认为没有)。

我试过用谷歌搜索这个问题,但似乎没有人遇到这个问题。

我还尝试创建一个 FileStream 来强制允许写入,并尝试提前关闭阅读器,但无济于事。我想我遗漏了一些如此明显的东西,但我终其一生都无法弄清楚。

Assembly assembly = Assembly.GetExecutingAssembly();
String filePath = assembly.Location.Substring(0, assembly.Location.LastIndexOf('.')) + " - Last Used Rounding";

RoundingIndex index = RoundingIndex.Nearest_8;  //The nearest 8th is the default.
if (File.Exists(filePath))
{
    using (StreamReader reader = new StreamReader(filePath))
    {
        try
        {
            int value = int.Parse(reader.ReadLine());

            foreach (RoundingIndex dex in Enum.GetValues(typeof(RoundingIndex)))
            {
                if (value == (int) dex)
                {
                    index = dex;

                    break;
                }
            }
        }
        catch
        {
            //Recreate the corrupted file.
            reader.Close();

            File.Delete(filePath);

            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine((int) index);
            }

            File.SetAttributes(filePath, FileAttributes.Hidden);
        }
    }
}
else
{
    using (StreamWriter writer = new StreamWriter(filePath))
    {
        writer.WriteLine((int) index);
    }

    File.SetAttributes(filePath, FileAttributes.Hidden);
}


//
//Process information here and get the next "last rounding".
//


using (StreamWriter writer = new StreamWriter(filePath))    //Exception getting thrown here.
{
    writer.WriteLine((int) RoundingIndex.Nearest_16);
}






//In case there is any question:
public enum RoundingIndex
{
    Nearest_2 = 2,
    Nearest_4 = 4,
    Nearest_8 = 8,
    Nearest_16 = 16,
    Nearest_32 = 32,
    Nearest_64 = 64,
    Nearest_128 = 128,
    Nearest_256 = 256
}

【问题讨论】:

  • 你不应该使用File.Exists 然后直接打开文件。它引入了竞争条件。只需尝试打开文件并处理FileNotFoundException
  • 我不太确定阅读器在使用部分之后是否真的关闭了,也许你应该尝试手动关闭阅读器。
  • stackoverflow.com/questions/2246990/… (请参阅 Lucero 的答案,而不是接受的答案)

标签: c# streamreader streamwriter


【解决方案1】:

您需要在修改其内容之前更改“隐藏”状态。

FileInfo myFile = new FileInfo(filePath);
myFile.Attributes &= ~FileAttributes.Hidden;

之后,您可以将状态设置回来

myFile.Attributes |= FileAttributes.Hidden;

【讨论】:

  • 效果很好,谢谢!我猜你不能修改隐藏文件,不知道。
猜你喜欢
  • 2017-06-12
  • 2014-03-11
  • 2012-06-03
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2020-11-17
相关资源
最近更新 更多