【发布时间】:2015-05-31 22:41:14
【问题描述】:
我试图从一个文本文件读取到一个数组,更改一个元素,然后将数组读回文件,但不附加原始文本。但它说该文件正在被另一个进程使用。任何帮助表示赞赏。
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");
}
}
【问题讨论】:
-
我倾向于将文件写入内存流,关闭 StreamReader 以释放文件,然后将 MemoryStream 中的内容写回文件。不确定这是否是最好的方法,但已经做了几次没有任何问题!
-
你甚至不使用 readName 和 readColour。
-
readName和readColour好像根本不用?而linesA和linesB你没有显示你在其中放置任何数据的位置...... -
for (int a = 0; a
标签: c# arrays text-files streamreader streamwriter