如何更改文本文件中的特定行

How do i change a specific line in a textfile

我试图从一个文本文件读入一个数组,更改一个元素,然后将数组读回文件但不附加原始文本。但是它说该文件正在被另一个进程使用。感谢任何帮助。

        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");
        }
    }

尝试在读写部分之间添加行 readColour.Close();

这部分打开文件 B 两次:

    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..