这个问题在这里已有答案:
我正在尝试在读取/使用默认值后写入隐藏文件。在尝试重新打开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
}
在修改其内容之前,您需要更改“隐藏”状态。
FileInfo myFile = new FileInfo(filePath);
myFile.Attributes &= ~FileAttributes.Hidden;
之后,您可以将状态设置回来
myFile.Attributes |= FileAttributes.Hidden;