【问题标题】:System.IO.IOException: 'The process cannot access the file because it is being used by another processSystem.IO.IOException: '该进程无法访问该文件,因为它正被另一个进程使用
【发布时间】:2020-07-14 10:37:41
【问题描述】:

我正在尝试保存我的 txt 文件,但是当我得到标题中的错误时?如果我使用 .CreateNew 我没有收到错误,但我想保存到我拥有的现有文件中?

        private void OpenFile_MouseDown(object sender, MouseEventArgs e)
        {
            Stream myStream;
            if (openFileDialog.ShowDialog() == DialogResult.OK) 
            {
               if ((myStream = openFileDialog.OpenFile()) != null)
                {
                    string strfilename = openFileDialog.FileName;
                    string filetext = File.ReadAllText(strfilename);
                    richTextBox.Text = filetext;

                }
            }
        }

        private void savefile_MouseDown(object sender, MouseEventArgs e)
        {
            
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
                using (Stream s = File.Open(saveFileDialog.FileName, FileMode.Append))
                using (StreamWriter sw = new StreamWriter(s))
                {
                    sw.Write(richTextBox.Text);
                }

        }

【问题讨论】:

  • 使用ProcExp.exe(或ProcExp64.exe)找出其他进程锁定了您的文件。

标签: c# winforms file save


【解决方案1】:

您应该处置myStream 变量。这就是您收到该错误的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多