【发布时间】: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