Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.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#_File In Use - Fatal编程技术网

C# 如何修复';另一个进程正在使用文件';错误

C# 如何修复';另一个进程正在使用文件';错误,c#,file-in-use,C#,File In Use,我创建了一个程序,可以通过datagridview修改.exe.config文件(app config)的内容,datagridview上显示了键值对。问题是,我有一个保存设置,它用用户键入的新值替换旧值。它会保存,下次打开时,该文件将被覆盖,但当我尝试加载配置文件以更新用户的设置时,会出现“文件被另一个进程使用”错误 代码如下: private XmlDocument m_XmlDoc; private FileStream fIn; private StreamRe

我创建了一个程序,可以通过datagridview修改.exe.config文件(app config)的内容,datagridview上显示了键值对。问题是,我有一个保存设置,它用用户键入的新值替换旧值。它会保存,下次打开时,该文件将被覆盖,但当我尝试加载配置文件以更新用户的设置时,会出现“文件被另一个进程使用”错误

代码如下:

    private XmlDocument m_XmlDoc;

    private FileStream fIn;
    private StreamReader sr;
    private StreamWriter sw;

    private OrderedDictionary m_Settings;

    private void ProgramConfig_Load(object sender, EventArgs e)
    {
        try
        {
            loadconfigfile(GatewayConfiguration.Properties.Settings.Default.Config);

            BindingList<KeyValueType> list = new BindingList<KeyValueType>();
            for (index = 0; index < m_Settings.Count; index++)
            {
                list.Add(new KeyValueType(keys[index], values[index].ToString()));
            }

            var source = new BindingSource();
            source.DataSource = list;
            dataGridView1.DataSource = source;
        }
        catch (Exception ex)
        {
            textBox1.Text = ex.Message;
        }
    }

    public void loadconfigfile(string configfile)
    {
        if (File.Exists(configfile))
        {
            m_XmlDoc = new XmlDocument();
            GatewayConfiguration.Properties.Settings.Default.Config = configfile;
            GatewayConfiguration.Properties.Settings.Default.Save();

            // Error Occurs here at the fIn, telling me that the file is currently in use and cannot be accessed.
            fIn = new FileStream(configfile, FileMode.Open, FileAccess.ReadWrite);
            sr = new StreamReader(fIn);
            sw = new StreamWriter(fIn);
            try
            {
                m_XmlDoc.LoadXml(sr.ReadToEnd());
                loadAppSettings();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        else
        {
            throw new FileNotFoundException(configfile + " does not exist.");
        }
    }

    private void loadAppSettings()
    {
        m_Settings = new OrderedDictionary();
        XmlNodeList nl = m_XmlDoc.GetElementsByTagName("setting");
        foreach (XmlNode node in nl)
        {
            try
            {
                m_Settings.Add(node.Attributes["name"].Value, node.ChildNodes[0].InnerText);
            }
            catch (Exception)
            {
            }
        }
    }

    private void SaveAppSettings_Click(object sender, EventArgs e)
    {
        // saves
        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
        DialogResult result = MessageBox.Show("Overwrite the old values with the new values?", "Save Settings?", buttons);
        if (result == DialogResult.No)
        {
            return;
        }
        int index = 0;
        string[] keys = new string[m_Settings.Keys.Count];
        m_Settings.Keys.CopyTo(keys, 0);
        for (index = 0; index < dataGridView1.Rows.Count; index++)
        {
            if ((string)dataGridView1[2, index].Value != string.Empty)
            {
                setAppSetting(keys[index], (string)dataGridView1[2, index].Value);
            }
        }
        // Updates datagrid by loading configfile again
        loadconfigfile(GatewayConfiguration.Properties.Settings.Default.Config);
        textBox1.Text = "Settings Saved. You may now exit.";
        m_savecounter++;
        dataGridView1.Update(); 
        dataGridView1.Refresh();
    }
private XmlDocument m_XmlDoc;
私人文件流fIn;
私人流动阅读器sr;
私人StreamWriter sw;
私人订购的字典m_设置;
私有void ProgramConfig_加载(对象发送方,事件参数e)
{
尝试
{
loadconfigfile(GatewayConfiguration.Properties.Settings.Default.Config);
BindingList=新建BindingList();
对于(索引=0;索引
该错误发生在SaveAppSettings下的loadconfigfile函数中。它告诉我它无法访问该文件,因为该文件被另一个进程使用。在再次打开文件并将其显示给用户之前,是否需要执行某些操作

非常感谢,


Tf.rz

在loadconfigfile()的末尾如何

fIn.Close()


基本上,您需要关闭完成后打开的任何流

您应该使用
语句在
中包装对流的访问,这样它将调用一个
Dispose()
方法来为您关闭流

using(fIn = new FileStream(configfile, FileMode.Open, FileAccess.ReadWrite))
{
   // working with file stream
}

PS:在某些地方,您可以通过放置空的
Catch(exception){}
块来隐藏潜在的异常,甚至可以使用堆栈跟踪reset doint
throw ex来重新刷新

您是正在编辑该文件的进程,因为您在编辑后没有关闭该文件

在再次读取之前,您需要关闭所有流

fIn.Close();
sr.Close();
sw.Close();

可能重复感谢您的提示回答,它不会立即更新,但编辑是一次性的,如果用户希望再次编辑,文件将不再使用,并正确加载。感谢您的回答!如果将来需要,我可能会转而使用这种方法。谢谢你的建议,我马上就去帮你。干杯谢谢你的回答,但泰成比你抢先一步^^