Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何编辑文本文件中的一行数据_.net_Vb.net - Fatal编程技术网

.net 如何编辑文本文件中的一行数据

.net 如何编辑文本文件中的一行数据,.net,vb.net,.net,Vb.net,我想用vb.net编辑文本文件中的特定行。 下面的示例是我在文本文件中的数据: Port1.txt 数据1 数据2 数据3 数据4 数据5 数据6 数据7 我想将文本文件中的data5第5行编辑为dataXX。我该怎么做 到目前为止,通过使用下面的代码,我只能访问列出的所有数据,而不是一行数据 Dim path As String = "c:\Users\EliteBook\Desktop\Port1.txt" Dim readText() As String = File.Read

我想用vb.net编辑文本文件中的特定行。 下面的示例是我在文本文件中的数据:

Port1.txt

数据1

数据2

数据3

数据4

数据5

数据6

数据7

我想将文本文件中的data5第5行编辑为dataXX。我该怎么做

到目前为止,通过使用下面的代码,我只能访问列出的所有数据,而不是一行数据

 Dim path As String = "c:\Users\EliteBook\Desktop\Port1.txt"

    Dim readText() As String = File.ReadAllLines(path)
    Dim s As String
    For Each s In readText
        MsgBox(s)
    Next

这将在msgbox中输出文本文件中列出的所有数据。如何访问特定的数据行而不是所有数据行?我根据Nahum Litvin的建议,通过使用错误的方法编辑了这个问题

就像这样,我手头没有编译器

string path = @"c:\temp\MyTest.txt";
string[] readText = File.ReadAllLines(path);
string[4] = "new data";
File.WriteAllLines(path, readText );

你使用了错误的方法

就像这样,我手头没有编译器

string path = @"c:\temp\MyTest.txt";
string[] readText = File.ReadAllLines(path);
string[4] = "new data";
File.WriteAllLines(path, readText );

Nahum的答案是正确的,但它是C语言。下面是等效的VB.NET,使用您在问题中发布的代码中的数据:

Dim path As String = "c:\Users\EliteBook\Desktop\Port1.txt"
Dim readText As String() = File.ReadAllLines(path)
readText(4) = "dataXX"
File.WriteAllLines(path, readText)
上面的代码将文件读入字符串数组,每个元素一行。然后将第5行中的元素4更改为dataXX,在这一行代码中:

readText(4) = "dataXX"

然后它将数组保存回文件,第5行读取dataXX。

Nahum的答案是正确的,但它是C。下面是等效的VB.NET,使用您在问题中发布的代码中的数据:

Dim path As String = "c:\Users\EliteBook\Desktop\Port1.txt"
Dim readText As String() = File.ReadAllLines(path)
readText(4) = "dataXX"
File.WriteAllLines(path, readText)
上面的代码将文件读入字符串数组,每个元素一行。然后将第5行中的元素4更改为dataXX,在这一行代码中:

readText(4) = "dataXX"

然后它将数组保存回文件,第5行读取dataXX。

我已经编辑了这个问题。ReadAllLines允许我读取文本文件中的所有数据。如何指定停止的位置?另外,我不明白为什么他们使用Dim s作为字符串,并为每个s.File.ReadAllLines返回一个字符串数组,每行一个数组元素。没有停止-它将整个文件读取到数组中。您可以通过数组中对应的索引访问所需的行-但不要忘记数组是以零为基的,因此第5行将是数组中的索引4。@Tim,那么我如何访问数组,因为当我使用MsgBoxs0时。它导致显示列0的数据。我已经编辑了这个问题。ReadAllLines允许我读取文本文件中的所有数据。如何指定停止的位置?另外,我不明白为什么他们使用Dim s作为字符串,并为每个s.File.ReadAllLines返回一个字符串数组,每行一个数组元素。没有停止-它将整个文件读取到数组中。您可以通过数组中对应的索引访问所需的行-但不要忘记数组是以零为基的,因此第5行将是数组中的索引4。@Tim,那么我如何访问数组,因为当我使用MsgBoxs0时。它导致显示列0的数据。这是d。