我试图从文本文件读入数组,更改一个元素然后将数组读回文件但不附加原始文本。但它说该文件正在被另一个进程使用。任何帮助表示赞赏。
using (StreamReader readName = new StreamReader("fileA"))
{
using (StreamReader readColour = new StreamReader("fileB"))
{
var lineCount = File.ReadLines("fileB").Count();
string[] linesA = new string[lineCount];
string[] linesB = new string[lineCount];
for (int a = 0; a < linesA.Length; a++)
{
if (linesA[a] == UserVariables.userNameC)
{
linesB[a] = UserVariables.colourC.ToString();
}
}
}
}
try
{
using (StreamWriter colourWrite = new StreamWriter("fileB"))
{
for (int a = 0; a < linesB.Length; a++)
colourWrite.WriteLine(linesB[a], false);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
}
答案 0 :(得分:3)
您正在尝试阅读fileB
两次,
using (StreamReader readColour = new StreamReader("fileB")) <-- this opens
the file
here and
leaves it
open
{
var lineCount = File.ReadLines("fileB").Count(); <-- this tries to open it,
read it and close it..
but it can't because
you have it open
above..
答案 1 :(得分:2)
这部分两次打开fileB:
using (StreamReader readColour = new StreamReader("fileB"))
{
var lineCount = File.ReadLines("fileB").Count();
答案 2 :(得分:1)
尝试在读取和写入部分之间添加行readColour.Close();