文件不能被访问,因为它正在被另一个进程使用

本文关键字:另一个 进程 不能 访问 因为 文件 | 更新日期: 2023-09-27 18:07:49

我对编码有点陌生,我一直在尝试替换文本文件中的单词,但当我执行程序时,它给了我"文件被另一个进程错误使用"

private void btnSave1_Click(object sender, EventArgs e)
        {
            string DOB = dateTimePicker1.Value.ToString();
            string Fname = txtBFirstName.ToString();
            string Lname = txtBLastName.ToString();
            string IDnum = txtBIDnum.ToString();
            string Address = txtBAddress.ToString();
            string nationality = txtBNationality.ToString();
            //string gender = cmbGender.SelectedItem.ToString();
           // string marrStatus = cmbMaritialStatus.SelectedItem.ToString();
            StreamReader read = null;
            //write to file
            try
            {
               // var lines = File.ReadAllLines("CV.txt");
                string line;
                read = new StreamReader("CurriculumVitae.txt");
                while ((line = read.ReadLine()) != null) 
                {
                    string text = File.ReadAllText("CurriculumVitae.txt");
                    text = text.Replace("Empty", DOB);
                    File.WriteAllText("CurriculumVitae.txt",
                                       File.ReadAllText("CurriculumVitae.txt")
                                       .Replace("empty",DOB));
                }

            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                read.Close();
            }
                //Open Next Form
                Education objNextForm = new Education();
                objNextForm.Visible = true;
}

文件不能被访问,因为它正在被另一个进程使用

这三行中的问题

read = new StreamReader("CurriculumVitae.txt");
string text = File.ReadAllText("CurriculumVitae.txt");
File.WriteAllText("CurriculumVitae.txt"
        ,File.ReadAllText("CurriculumVitae.txt").Replace("empty",DOB));

StreamReader和File。ReadAllText将锁定文件。当它们试图锁定同一个文件时就会出错

你应该试着做一件事。不要多次打开文件。在文件关闭前不要打开它

您可以在代码中去掉这一部分,因为您没有使用您创建的StreamReader:

    while ((line = read.ReadLine()) != null) 
    {
    ...
    }

和改变File.WriteAllText("CurriculumVitae.txt",File.ReadAllText("CurriculumVitae.txt");

    File.WriteAllText("CurriculumVitae.txt", text);

你将需要更新你的StreamReader以"shared"模式打开文件,这样它就不会锁定文件。

首先,当您使用File.ReadAllText时不要使用StreamReader,因为它不需要,另一个错误来自这一行:

File.WriteAllText("CurriculumVitae.txt", File.ReadAllText("CurriculumVitae.txt").Replace("empty", DOB));

如果你打开了同一个文件两次,试试这样做:

string content = File.ReadAllText("CurriculumVitae.txt").Replace("empty", DOB);
File.WriteAllText("CurriculumVitae.txt", content);

使用StreamReaderReadAllText,但不能同时使用两者…此外,我真的建议尽可能使用"using",因为这有助于关闭许多对象(但不是您在这里的主要问题)

// It will free resources on its own.
//
using (StreamReader reader = new StreamReader("file.txt"))
{
    line = reader.ReadLine();
}
Console.WriteLine(line);
}