gpt4 book ai didi

c# - C# 中的文件 - "file is used by another process"

转载 作者:行者123 更新时间:2023-12-02 15:49:33 25 4
gpt4 key购买 nike

我有以下代码:

private void askforlocation()
{
if (File.Exists("location.txt"))
{
System.IO.StreamReader loc = new System.IO.StreamReader("location.txt");
string loca = loc.ReadToEnd();
if (loca != "")
{
int index = comboBox1.FindString(loca);
comboBox1.SelectedIndex = index;
}
else
{
label6.Text = "Please select the location!";
}
loc.Close();
}
else label6.Text = "Please select the location!";
}

它应该从文件中读取值“位置”并将其放入组合框,工作正常。

我在 Form1_Load 上运行此脚本。

现在,我有另一个脚本:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = comboBox1.SelectedItem.ToString();
System.IO.File.WriteAllText("location.txt", value);
}

这个应该记录选择,这样用户就不需要每次都输入位置。

发生的事情是当我启动一个程序时,所以该值已经设置,然后我尝试更改它(这样理论上它应该覆盖前一个),但我得到一个异常,说该文件已经被被另一个进程使用。

我在使用后确实关闭了该文件。我还尝试了FILE.DISPOSE

我做错了什么?

最佳答案

我认为这里发生的是这段代码:

if (loca != "")
{
int index = comboBox1.FindString(loca);
comboBox1.SelectedIndex = index;
}

导致组合框上引发 SelectedIndexChanged 事件。引发该事件时,将调用 comboBox1_SelectedIndexChanged,并且该方法再次尝试访问 location.txt

要解决此问题,我首先将 askforlocation 中的代码更改为如下所示:

if (File.Exists("location.txt"))
{
var loca = string.Emtpy;
using(var loc = new System.IO.StreamReader("location.txt"))
{
loca = loc.ReadToEnd();
}
....
}

因为无需将文件保持打开状态超过必要的时间(请注意,using block 将调用 StreamReader< 上的 Dispose() 方法 当它退出时,它又会调用 Close() 方法)。之后,我会考虑想出一种方法,当您在组合框上设置选定的索引时,防止事件被触发(可能使用标志或取消/重新连接事件处理程序)。

关于c# - C# 中的文件 - "file is used by another process",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7925307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com