System.IO.IOException: 'The process cannot access the file because it is being used by another process

£可爱£侵袭症+ 提交于 2020-07-16 07:56:13

问题


i'm trying to save my txt file, but when i do i get the error in the title? if i use .CreateNew i dont get the error, but i want to save to the existing file i have?

        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);
                }

        }

回答1:


You should dispose myStream variable. That's why you are getting that error.



来源:https://stackoverflow.com/questions/62893258/system-io-ioexception-the-process-cannot-access-the-file-because-it-is-being-u

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!