当我写入文件并替换文件中包含的字符串并且我不知道如何解决它时,我收到此错误:
该进程无法访问文件' C:\ WarThunder \ config.blk'因为它正被另一个进程使用。
我已经尝试关闭我打开的所有可以托管这些文件数据的内容,但我觉得这可能是我对代码的低效使用造成的。以前不是问题。我不记得它何时出现:/
对于其他两个复选框,以下代码重复一次:
private void rdbDX11_CheckedChanged(object sender, EventArgs e)
{
if (rdbDX11.Checked == true)
{
pbOGL3Outer.Visible = false;
pdDX11Outer.Visible = true;
pdDX9Outer.Visible = false;
rdbDX9.Checked = false;
rdbOGL3.Checked = false;
Properties.Settings.Default.varRenderSelected = ("DirectX11");
using (StreamReader ReadConfig = new StreamReader(Properties.Settings.Default.SavedConfig))
{
while (ReadConfig.Peek() != 1) //While not end of file
{
var ReWriteFile = File.ReadAllText(Properties.Settings.Default.SavedConfig);
if (ReWriteFile.Contains(" driver:t=\"dx9\""))
{ ReWriteFile = ReWriteFile.Replace(" driver:t=\"dx9\"", " driver:t=\"dx11\""); }
else if (ReWriteFile.Contains(" driver:t=\"gl3\""))
{ ReWriteFile = ReWriteFile.Replace(" driver:t=\"gl3\"", " driver:t=\"dx11\""); }
else if (ReWriteFile.Contains(" driver:t=\"auto\""))
{ ReWriteFile = ReWriteFile.Replace(" driver:t=\"auto\"", " driver:t=\"dx11\""); }
System.IO.File.WriteAllText(Properties.Settings.Default.SavedConfig, ReWriteFile);
}
}
}
}
答案 0 :(得分:3)
你所要做的就是
类似的东西:
private void rdbDX11_CheckedChanged(object sender, EventArgs e)
{
if (rdbDX11.Checked == true)
{
pbOGL3Outer.Visible = false;
pdDX11Outer.Visible = true;
pdDX9Outer.Visible = false;
rdbDX9.Checked = false;
rdbOGL3.Checked = false;
Properties.Settings.Default.varRenderSelected = ("DirectX11");
// Read
var ReWriteFile = File.ReadAllText(Properties.Settings.Default.SavedConfig);
// Edit
ReWriteFile = ReWriteFile
.Replace(" driver:t=\"dx9\"", " driver:t=\"dx11\"")
.Replace(" driver:t=\"gl3\"", " driver:t=\"dx11\"")
.Replace(" driver:t=\"auto\"", " driver:t=\"dx11\"");
// Write back
File.WriteAllText(Properties.Settings.Default.SavedConfig, ReWriteFile);
}
}
答案 1 :(得分:2)
这一行:
System.IO.File.WriteAllText(Properties.Settings.Default.SavedConfig, ReWriteFile);
无法写信至Properties.Settings.Default.SavedConfig
,因为您在同一个文件中打开了StreamWriter
,您在using
声明中打开了该文件:
using (StreamReader ReadConfig = new StreamReader(Properties.Settings.Default.SavedConfig))
没有理由创建此StreamReader
或使用while
循环。您正在使用以下行读取文件的全文:
var ReWriteFile = File.ReadAllText(Properties.Settings.Default.SavedConfig);
失去using
区块;丢失while
循环。一切都好。