Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用C语言编写的文件;文件被另一个进程使用;_C#_.net - Fatal编程技术网

C# 用C语言编写的文件;文件被另一个进程使用;

C# 用C语言编写的文件;文件被另一个进程使用;,c#,.net,C#,.net,我有以下代码: private void askforlocation() { if (File.Exists("location.txt")) { System.IO.StreamReader loc = new System.IO.StreamReader("location.txt"); string loca = loc.ReadToEnd();

我有以下代码:

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!";        
        }
它应该从文件中读取值“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


我做错了什么?

组合框1.SelectedIndex=index; 这将触发SelectedIndexChanged事件,因此调用ReadToEnd()后面的Close()方法:


似乎您正在更改组合框的索引,从而在关闭它之前写入同一个文件。在再次写入文件之前调用loca.Close(),因为事件的引发时间比您想象的要早。

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

if (loca != "")
{
    int index = comboBox1.FindString(loca);
    comboBox1.SelectedIndex = index;
}
正在导致组合框上引发
SelectedIndexChanged
事件。当引发该事件时,将调用
comboBox1\u 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
块在退出时将调用
StreamReader
上的
Dispose()
方法,该方法反过来将调用
Close()
方法)。之后,我会考虑一种方法,当你在组合框上设置所选索引时,可以防止事件被触发(可能使用标志或unWele/Read事件处理程序)。p> 在使用实现IDisposable的类时,请始终(或主要)使用using语句。它将为您调用Dispose方法

using(System.IO.StreamReader loc = new System.IO.StreamReader("location.txt"))
{
    string loca = loc.ReadToEnd();
}

有一点很重要,那就是向阅读此答案的任何人指出,将文件读取封装在“using”块中会隐式调用Close()方法。
using(System.IO.StreamReader loc = new System.IO.StreamReader("location.txt"))
{
    string loca = loc.ReadToEnd();
}