尝试使用先前打开的文件打开StreamWriter时发生System.UnauthorizedAccessException

时间:2019-04-16 14:23:42

标签: c# streamreader streamwriter

我正在尝试读取/使用默认值后写入隐藏文件。尝试重新打开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
}

1 个答案:

答案 0 :(得分:0)

您需要先更改“隐藏”状态,然后再修改其内容。

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

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

myFile.Attributes |= FileAttributes.Hidden;