C# 如何更改文本文件中的特定行
我正在尝试从文本文件读入数组,更改一个元素,然后将数组读回文件,但不追加原始文本。但是它说这个文件正在被另一个进程使用。感谢您的帮助C# 如何更改文本文件中的特定行,c#,arrays,text-files,streamreader,streamwriter,C#,Arrays,Text Files,Streamreader,Streamwriter,我正在尝试从文本文件读入数组,更改一个元素,然后将数组读回文件,但不追加原始文本。但是它说这个文件正在被另一个进程使用。感谢您的帮助 using (StreamReader readName = new StreamReader("fileA")) { using (StreamReader readColour = new StreamReader("fileB")) { var
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 readName=newstreamreader(“fileA”))
{
使用(StreamReader ReadColor=新的StreamReader(“文件B”))
{
var lineCount=File.ReadLines(“fileB”).Count();
string[]linesA=新字符串[lineCount];
string[]linesB=新字符串[lineCount];
对于(int a=0;a
尝试添加行readcolor.Close()
在读写部分之间尝试添加行readcolor.Close()代码>在读和写部分之间此部分将打开文件B两次:
using (StreamReader readColour = new StreamReader("fileB"))
{
var lineCount = File.ReadLines("fileB").Count();
此部分将打开fileB两次:
using (StreamReader readColour = new StreamReader("fileB"))
{
var lineCount = File.ReadLines("fileB").Count();
您试图读取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..
使用(streamreadcolor=newstreamreader(“fileB”)您试图读取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..
使用(streamreadcolor=newstreamreader(“fileB”))我倾向于将文件写入内存流,关闭StreamReader释放文件,然后将内存流中的内容写回文件。不确定这是否是最好的方式,但已经做了几次没有任何问题!您甚至不使用readName和ReadColor。readName
和ReadColor
似乎根本不使用?和linesA
和linesB
您不显示将任何数据放入其中的位置…对于(int a=0;areadName
和ReadColor
似乎根本不使用?和linesA
和linesB
您不显示将任何数据放在其中的位置…(int a=0;a