很难在.TXT文件中编写NewLine

时间:2015-07-30 22:30:42

标签: vb.net

基本上我正在做的是编写一个从网站引用引用并将其写入.txt文件的程序。它工作正常,但我不知道谁将NewLine添加到.txt文件中。我只会告诉你代码。

If Not div Is Nothing Then
        Dim blank As String = Environment.NewLine
        Dim finish As String = (div.InnerText.Trim())
        TextBox2.Text = Chr(34) & finish & Chr(34)
        Dim fileName As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt")
        My.Computer.FileSystem.WriteAllText(fileName, Chr(34) & finish & Chr(34), True)
        My.Computer.FileSystem.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("userprofile"), "Documents\Horoscope\Monthly.txt"), blank, True)
        My.Computer.FileSystem.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("userprofile"), "Documents\Horoscope\Monthly.txt"), blank, True)
    End If

现在对于第一对引号工作正常,但是由于我删除了重复项的另一部分代码,它之后的任何内容都不会缩进。

Dim lines As String() = IO.File.ReadAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"))
    lines = lines.Distinct().ToArray()
    IO.File.WriteAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"), lines)

我是否有另一种方法可以在文本文件中的引号之间产生差距?

1 个答案:

答案 0 :(得分:1)

删除重复项时,您可以删除包含Where的现有空白行,然后使用lines将其重新添加到SelectMany数组中:

lines = lines.
    Where(Function(x) Not String.IsNullOrEmpty(x)).
    Distinct().
    SelectMany(Function(x) { x, String.Empty }).
    ToArray()

SelectManyDistinct后面的每一行留下一行,加上一个空格。

您可能还想在添加新条目时使用File.AppendAllLines - 看起来更清洁一点:

File.AppendAllLines(fileName, { Chr(34) & finish & Chr(34), ""})

修改

这将适合您的代码:

If Not div Is Nothing Then
    Dim finish As String = (div.InnerText.Trim())
    TextBox2.Text = Chr(34) & finish & Chr(34)
    Dim fileName As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt")
    IO.File.AppendAllLines(fileName, { Chr(34) & finish & Chr(34), ""})
End If
'...
Dim lines As String() = IO.File.ReadAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"))
lines = lines.
    Where(Function(x) Not String.IsNullOrEmpty(x)).
    Distinct().
    SelectMany(Function(x) { x, String.Empty }).
    ToArray()
IO.File.WriteAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"), lines)