无法访问文件,因为它正由另一个进程使用

时间:2015-08-12 15:57:32

标签: c#

我对编码很新,我一直试图替换文本文件中的单词,但是当我执行程序时,它给了我"文件被另一个进程错误使用& #34;

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;

}

5 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

这3行问题

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都将锁定文件。每当他们试图锁定同一个文件时,都会出错

你应该尝试做一次事。不要尝试多次打开文件。并且在关闭之前不要打开同一个文件

答案 2 :(得分:0)

您可以在代码中取出此部分,因为您没有使用您创建的StreamReader:

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

改变         File.WriteAllText(" CurriculumVitae.txt&#34 ;,             File.ReadAllText(" CurriculumVitae.txt&#34);

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

答案 3 :(得分:0)

您需要更新StreamReader才能在" shared"中打开文件。模式,以便它不会锁定文件。

有关如何执行此操作的详细信息,请参阅this question

答案 4 :(得分:0)

使用StreamReaderReadAllText,但不能同时使用两者...... 另外我真的建议尽可能做“使用”,因为这有助于很多关闭对象(但这不是你的主要问题)

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