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



我得到一个错误,我的文本文件是用来创建和保存我的字典正在被另一个进程使用,我已经使用进程资源管理器到什么可以使用我的文件没有结果。下面是我的代码和抛出这个错误的代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace meade_9_10
{
public partial class Form1 : Form
{
private Dictionary<string, string> names = new Dictionary<string, string>()
{

};
public Form1()
{
//Make sure Form1 is loaded and ran on program open
InitializeComponent();
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
//Grab myfile.txt and convert to array
StreamReader sr = new StreamReader("myfile.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
string[] arr = line.Split(',');
int i = 0;
//Add array objects to names dictionary
while (i < arr.Length)
{
names[arr[i]] = arr[i + 1];
i += 2;
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{   
//declare variables
string nameAdd;
string emailAdd;
//Put user input into variable
nameAdd = txtNameAdd.Text;
emailAdd = txtEmailAdd.Text;
//Declare new dictionary key pair as user input
names[emailAdd] = nameAdd;
//clear the textbox controls
txtNameAdd.Text = "";
txtEmailAdd.Text = "";
}
private void btnDelete_Click(object sender, EventArgs e)
{   
string emailDel;
emailDel = txtEmailDel.Text;
//Remove key pair that is inputted by user
names.Remove(emailDel);   
}
private void btnChange_Click(object sender, EventArgs e)
{
//Declare variables
string emailDel;
string nameAdd;
string emailAdd;
//Assign values to variables
emailDel = txtEmailChange.Text;
nameAdd = txtNameNew.Text;
emailAdd = txtEmailNew.Text;
//Delete the user inputted email to change
names.Remove(emailDel);
//Add the new key pair values to dictionary
names.Add(emailAdd, nameAdd);
}
private void btnLookUp_Click(object sender, EventArgs e)
{  
//Declare variable
string email = txtEmail.Text;
//If statement to check if dictionary contains key value
if (names.ContainsKey(email))
{
outputName.Text = names[email];
outputEmail.Text = email;
}   
}
private void btnExit_Click(object sender, EventArgs e)
{
//writes the names dictioanry to array inside text file
File.WriteAllLines("myfile.txt",
names.Select(x => x.Key + "," + x.Value ).ToArray());

//Closes the program
this.Close();
}
}
}

给出错误

的那部分代码先。IOException: '进程无法访问文件'C:UsersAdrianDesktopALL SCHOOL FILESFall 2021 c# meade_9_10binDebugmyfile.txt',因为它正在被另一个进程使用。'

names.Select(x => x.Key + "," + x.Value ).ToArray());

我只是无法弄清楚是什么过程使用我的文本文件破坏了这个程序,它早些时候工作,我没有做任何改变,除了删除函数之间多余的空白。

尝试使用在最内层的while循环之后的StreamReader.Close()方法:

关闭StreamReader对象和底层流,并释放与reader相关的所有系统资源。

或者,您可以使用using语句:

提供方便的语法,确保正确使用IDisposable对象。

相关内容