将路径保存到txt文件(VB.net)

时间:2019-08-06 08:38:53

标签: vb.net

因此,基本上,我正在执行“另存为”按钮,并且在保存文件时,我希望从保存的文件到另一个txt文件的路径完全不同。

Private Sub saveas_Click(sender As Object, e As EventArgs) Handles Saveas.Click
    SaveFileDialog1.InitialDirectory = "C:\Users\marce"
    SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
    SaveFileDialog1.FilterIndex = 2
    SaveFileDialog1.ShowDialog()

    Dim W As New IO.StreamWriter(SaveFileDialog1.FileName)
    W.Write(RichTextBox1.Text)
    W.Close()
End Sub

2 个答案:

答案 0 :(得分:1)

那么,您的问题也正在写入另一个文件吗?还是以某种方式从SaveFileDialog返回两个不同的文件名?如果是后者,我不认为这可以做到。

如果是前者,则您已经知道如何写入文本文件,因此此答案似乎是多余的。仍然,以下代码(假定“完全不同的txt文件”是通过在原始文件名后附加“ .tmp”来命名的)将原始路径保存到第二个文件:

Private Sub saveas_Click(sender As Object, e As EventArgs) Handles Saveas.Click
    SaveFileDialog1.InitialDirectory = "C:\Users\marce"
    SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
    SaveFileDialog1.FilterIndex = 2
    SaveFileDialog1.ShowDialog()

    Dim W As New IO.StreamWriter(SaveFileDialog1.FileName)
    W.Write(RichTextBox1.Text)
    W.Close()

    'new code
    'get new filename by appending .tmp to the original filename
    Dim tmpFilePath As String = SaveFileDialog1.FileName & ".tmp"
    IO.File.WriteAllText(tmpFilePath, SaveFileDialog1.FileName)
End Sub

答案 1 :(得分:1)

要添加到 @Spyros P的答案中,我将SaveFileDialog1.ShowDialog()存储到变量中,因为如果您cancel or X out of the Save window仍将继续保存文件。可能会这样:

Private Sub saveas_Click(sender As Object, e As EventArgs) Handles Saveas.Click
    SaveFileDialog1.InitialDirectory = "C:\Users\marce"
    SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
    SaveFileDialog1.FilterIndex = 2
    Dim temp = SaveFileDialog1.ShowDialog()

    If temp = False Then Return

    Dim W As New IO.StreamWriter(SaveFileDialog1.FileName)
    W.Write(RichTextBox1.Text)
    W.Close()

    'new code
    'get new filename by appending .tmp to the original filename
    Dim tmpFilePath As String = SaveFileDialog1.FileName & ".tmp"
    IO.File.WriteAllText(tmpFilePath, SaveFileDialog1.FileName)
End Sub

总体上 @Spyros P。是正确的,我所做的更改只是添加了SaveFileDialog1.ShowDialog

的变量