我正在做一个项目Windows窗体的Uni分配,我想搜索一个已经创建的文本文件来匹配名字和姓氏,然后写入一些额外的信息,如果姓名和姓氏存在。我构建了代码并且没有显示任何错误,但是当我运行并尝试添加信息时,我被提供了一个基本上表示下一个进程的错误(Streamreader编写器无法访问该文件,因为它已被另一进程使用)我假设这个过程是streamreader,我试图编码它停止阅读无济于事。我在我的前3个月学习编码,如果可能的话,我会感谢一些帮助,我已经把我的代码片段放在下面。c#如何结束流读取器
//check if there is a file with that name
if (File.Exists(sFile))
{
using (StreamReader sr = new StreamReader(sFile))
{
//while there is more data to read
while (sr.Peek() != -1)
{
//read first name and last name
sFirstName = sr.ReadLine();
sLastName = sr.ReadLine();
}
{
//does this name match?
if (sFirstName + sLastName == txtSearchName.Text)
sr.Close();
}
//Process write to file
using (StreamWriter sw = new StreamWriter(sFile, true))
{
sw.WriteLine("First Name:" + sFirstName);
sw.WriteLine("Last Name:" + sLastName);
sw.WriteLine("Gender:" + sGender);
}
StreamReader的右括号在哪里。 using指令将处理流读取器并释放它对文件的锁定,但是看起来好像在打开作者之后才会关闭它? – Wheels73
读取输入文件,写入临时文件,然后用临时文件压碎输入文件。 –
你确定你的代码的这部分被执行了吗?因为它似乎在尝试同时读取和写入同一个文件。 (看起来像一个可怕的想法) –