【问题标题】:How do i change a specific line in a textfile如何更改文本文件中的特定行
【发布时间】: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。
  • readNamereadColour 好像根本不用?而linesAlinesB 你没有显示你在其中放置任何数据的位置......
  • for (int a = 0; a

标签: c# arrays text-files streamreader streamwriter


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这部分打开fileB两次:

        using (StreamReader readColour = new StreamReader("fileB"))
        {
    
            var lineCount = File.ReadLines("fileB").Count();
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-30
        • 2020-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多