如何从文件中的特定行删除文本而不使用C#创建不需要的空间? [英] How to remove text from a specific line in file without creating unwanted space using C#?

查看:65
本文介绍了如何从文件中的特定行删除文本而不使用C#创建不需要的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我创建的文件中的特定行中删除文本Test.txt。



这是用Test编写的文本.txt:

1

2

3

4

5 br />


7

8

9

10



现在我想要发生的是当我要删除1-5时,数字6 - 10应该替换1-5的线。喜欢这个:

6

7

8

9

10 br />


但是当我尝试代码时它给了我这个输出:











6

7

8

9

10



正如你可以看到上面的输出,这就是我所说的不需要的空间。



我尝试过:



这是我尝试过的代码:



I'm trying to remove text from a specific line in the file that i have created "Test.txt".

Here is the text written in Test.txt:
1
2
3
4
5
6
7
8
9
10

Now what i want to happen is when i'm going to remove 1-5, the numbers 6 - 10 should replace the line for 1-5. Like this:
6
7
8
9
10

But when i tried the code it gave me this output:





6
7
8
9
10

As you can see the above output, that is the unwanted space that i'm talking about.

What I have tried:

Here is the code that I have tried:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestCode
{
class Program2
{
    static void Main()
    {
        lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 1);
        lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 2);
        lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 3);
        lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 4);
        lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 5);
    }

    static void lineChanger(string newText, string fileName, int line_to_edit)
    {
        string[] arrLine = File.ReadAllLines(fileName);
        arrLine[line_to_edit - 1] = newText;
        File.WriteAllLines(fileName, arrLine);
    }
}
}





另外,请随时提出任何适当的技巧,并请包括实际示例。



Also please feel free to suggest any proper techniques and kindly include actual examples.

推荐答案

使用列表而不是数组使其更容易。



Using a list instead of an array makes it easier.

static void lineChanger(string newText, string fileName, int line_to_edit)
{
    List<string> arrLine = File.ReadAllLines(fileName).ToList();
    if (arrLine.Count <= line_to_edit)
    { 
        if (string.IsNullOrEmpty(newText))
        {
            arrLine.RemoveAt(line_to_edit - 1);
        }
        else
        {
            arrLine[line_to_edit-1] = newText;
        }
        File.WriteAllLines(fileName, arrLine.ToArray());
    }
    else
    {
        throw new Exception(string.Format("File does not contain {0} lines. Operation aborted.", line_to_edit));
    }
}


这篇关于如何从文件中的特定行删除文本而不使用C#创建不需要的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆