C# 尝试使用以前打开的文件打开StreamWriter时System.UnauthorizedAccessException

C# 尝试使用以前打开的文件打开StreamWriter时System.UnauthorizedAccessException,c#,streamreader,streamwriter,C#,Streamreader,Streamwriter,我试图在读取/使用默认值后写入隐藏文件。在尝试重新打开StreamWriter后,我得到一个UnauthorizedAccessException,告诉我对文件的访问被拒绝,但其中没有任何有用的信息(至少我认为没有) 我曾尝试在谷歌上搜索这个问题,但似乎没有人碰到这个问题 我还尝试创建一个文件流来强制允许写入,并尝试提前关闭读卡器,但没有效果。我想我错过了一些显而易见的东西,但我一辈子都想不出来 Assembly assembly = Assembly.GetExecutingAssembly(

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

我曾尝试在谷歌上搜索这个问题,但似乎没有人碰到这个问题

我还尝试创建一个文件流来强制允许写入,并尝试提前关闭读卡器,但没有效果。我想我错过了一些显而易见的东西,但我一辈子都想不出来

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
}

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

FileInfo myFile = new FileInfo(filePath);
myFile.Attributes &= ~FileAttributes.Hidden;
之后,您可以将状态设置回原来的状态


myFile.Attributes |=FileAttributes.Hidden

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

FileInfo myFile = new FileInfo(filePath);
myFile.Attributes &= ~FileAttributes.Hidden;
之后,您可以将状态设置回原来的状态


myFile.Attributes |=FileAttributes.Hidden

您不应该使用
文件。存在
,然后直接打开文件。它引入了竞争条件。只需尝试打开文件并处理
FileNotFoundException
。我不太确定在使用部分之后是否真的关闭了读卡器,也许您应该尝试手动关闭读卡器。(请参阅Lucero的答案,不是公认的答案)您不应该使用
File.Exists
,然后直接打开该文件。它引入了竞争条件。只需尝试打开文件并处理
FileNotFoundException
。我不太确定在使用部分之后是否真的关闭了读卡器,也许您应该尝试手动关闭读卡器。(见卢塞罗的答案,不是公认的答案)这非常有效,谢谢!我猜你不能修改隐藏的文件,我不知道。这非常有效,谢谢!我猜你不能修改隐藏的文件,我不知道。