如何在不使用C#覆盖当前文本的情况下在特定行中写入文本? [英] How to write text in a specific line without overwriting the current text using C#?

查看:94
本文介绍了如何在不使用C#覆盖当前文本的情况下在特定行中写入文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在特定行中编写新文本,而没有完全覆盖文件的当前内容,但我似乎无法使其工作。例如,在我的文件名为Test.txt中,这是当前写的:



1

2

3

4



8

9

10 br />


您可能已经注意到,我没有包括数字5,6和7.还有一个空间,您可以插入5,6和7.但作为我尝试插入这些数字,它给我这个输出:



1

2

3

4



8

9

$

2

3

4



5

$

7



显然我添加了一堆我不想要的数字。代码如下所示。希望你们可以帮我这个。



我尝试过:



 命名空间 TestCode 
{
class Program2
{
static void Main()
{

var lines = System.IO.File.ReadAllLines( @ < span class =code-string> C:\Users\User1 \Documents\Visual Studio 2015 \WebSites\MusicStore \Pages \Test.txt);
行[ 5 ] = 5 ;
行[ 6 ] = 6 ;
行[ 7 ] = 7 ;
System.IO.File.AppendAllLines( @ C:\ Users \ User1 \Documents \\ \\ Visual Studio 2015 \WebSites\MusicStore \Pages \Test.txt,行);



}
}
}

解决方案

您的问题是 AppendAllLines 。该方法将您正在写入的内容添加到文件末尾。请改用 WriteAllLines



此外,您的插入行是替代品。有几种方法可以解决这个问题。你可以

1.使用列表而不是数组,并在适当的位置插入行。

2.创建一个行数正确的新数组,并将读取值复制到正确的位置。

3.设置行[4] =5+ Environment.NewLine +6+ Environment.NewLine +7+ Environment.NewLine



**注意 - 行的索引需要基于零,因此它们比行中的数字少1。


正如你的问题评论中NotPoliticallyCorrect已经提到的,AppendAllLines只会将列表附加到当前数据。没有更多,没有更少。



为了添加5,6,7(对于当前数据并且仅适用于此场景),您还需要稍后对数据进行排序。对数据进行排序将相应地排列行。

  //  读取数据 
var lines = File.ReadAllLines( path );
var _lines = new 列表< string>(行); // string [] to List< string>

_lines.Add( 5);
_lines.Add( 6);
_lines.Add( 7);
lines = _lines.ToArray(); // 回来。

// sort
Array.Sort(lines);

// 写入数据
File.WriteAllLines(< span class =code-string>
path,lines);



那个将按顺序写入数据。您也可以考虑在这里使用LINQ,这将为代码提供更好的可读性,但这需要更多的修补才能使代码工作。



还有一件事,因为数据是字符串类型,排序就像1,10,2 ......而不是1 ,2,... 10,使用您需要将数据转换为整数然后对其进行排序的后一个。为此,您应该查看 Convert.ToInt32()方法,并在排序之前使用它将列表转换为整数。



举个例子,请看这里, .NET小提琴 [ ^ ]


< blockquote>当你不理解你的代码在做什么或为什么它做它的作用时,答案是调试器

使用调试器来查看你的代码是什么这样做。它允许你逐行执行第1行并在执行时检查变量,它是一个令人难以置信的学习工具。



调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做的比较。

调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。


I've been trying to write new texts in a specific line without completely overwriting the current contents of the file but I can't seem to make it work. For example, in my file called Test.txt, This is whats currently written in it:

1
2
3
4

8
9
10

As you may have noticed, I did not inlude the numbers 5,6 and 7. There is also a space where you can insert 5,6 and 7. But as i tried inserting those numbers, its giving me this output:

1
2
3
4

8
9
101
2
3
4

5
6
7

It clearly have added a bunch of numbers that I did not want. Code for this is indicated below. Hope you guys can help me on this one.

What I have tried:

namespace TestCode
{
    class Program2
    {
        static void Main()
        {

            var lines = System.IO.File.ReadAllLines(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt");
            lines[5] = "5";
            lines[6] = "6";
            lines[7] = "7";
            System.IO.File.AppendAllLines(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", lines);

            

        }
    }
}

解决方案

Your problem is AppendAllLines. That method adds whatever you are writing to the end of the file. Use WriteAllLines instead.

Also, your insertion of lines is a replacement. There are a few ways of fixing that. You can
1. Use a list instead of an array, and Insert the lines in the appropriate place.
2. Create a new array with the correct number of rows, and copy the read values into the right places.
3. Set lines[4] = "5" + Environment.NewLine + "6" + Environment.NewLine + "7" + Environment.NewLine

**Note - the indexes of the lines need to be zero based, so they are 1 less than the number you have in the line.


As already mentioned by NotPoliticallyCorrect in the comment to your question, the AppendAllLines will only append the list to your current data. Nothing more, nothing less.

In order to add 5,6,7 (to the current data and only applicable to this scenario), you also need to later sort the data. That sorting of the data will arrange the lines accordingly.

// read the data
var lines = File.ReadAllLines("path");
var _lines = new List<string>(lines); // string[] to List<string>

_lines.Add("5");
_lines.Add("6");
_lines.Add("7");
lines = _lines.ToArray(); // Come back.

// sort
Array.Sort(lines);

// Write the data
File.WriteAllLines("path", lines);


That will write the data in sequence. You can consider using LINQ here as well, that will give a better readability for the code, but that would require a bit more tinkering to get the code to work.

One more thing, since the data is of string type, the sorting will be like, "1, 10, 2..." and not like, "1, 2,... 10", to use the later one you need to cast the data to integer and then sort it. For that you should look at, Convert.ToInt32() method and use that to convert the list to integers before sorting it.

For an example, please have a look here, Home | .NET Fiddle[^]


When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. It allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


这篇关于如何在不使用C#覆盖当前文本的情况下在特定行中写入文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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