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

亚当·希金斯

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

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

您正在尝试阅读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..

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在文本文件的特定行中更改单独的文本

如何更改文本文件中的特定值?

如何从文本文件中删除特定行?

如何从PHP中的文本文件读取特定行

如何只读取文本文件中的特定行?

如何删除文本文件中的特定行?

如何提取文本文件中的特定行

如何提取/更改文本文件中的行,该文本文件的数据分为多个字段?

在同时对文本文件进行某些操作之后,如何删除该文本文件中的特定行

如何從文本文件打印特定的行/行?

Python如何替换文本文件中特定行中的特定单词?

如何从文本文件中读取特定行和文本

在Python中编辑文本文件中的特定行

如何在文本文件的特定行中更新特定值C#

如何提取文本文件中的特定行以及包含特定字符串的多行?

如何将文本文件中的特定行保存到特定数组?

查找文本文件中要更改的行的条件

如何通过输入文件从具有特定值的文本文件中删除行?

如何根据条件(大于或小于)打印出文本文件中的特定行/行

删除特定行后如何删除文本文件中的空白行?

从Java中的文本文件读取特定行

从文本文件中删除特定行

从Java中的文本文件读取特定行

替换文本文件中的特定行

从.NET中的文本文件确定特定行的行数

使用perl从文本文件中打印特定行

替换为文本文件特定行中的行号

以编程方式修改文本文件中的特定行

从文本文件中获取特定行的最快方法