System.UnauthorizedAccessException 尝试使用之前打开的文件打开 StreamWriter

System.UnauthorizedAccessException when trying to open a StreamWriter with a previously opened file

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

我尝试用谷歌搜索这个问题,但似乎没有人运行进入这个问题。

我也试过创建一个 FileStream 来强制允许写入,也试过预先关闭 reader,但无济于事。我想我遗漏了一些如此明显的东西,但我一辈子都弄不明白。

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
}

您需要先更改 'hidden' 状态才能修改其内容。

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

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

myFile.Attributes |= FileAttributes.Hidden;