如何使用StreamWriter将文件保存在所需的路径中

时间:2014-04-23 05:29:01

标签: vb.net

我通过使用StreamWriter提供路径来保存目录中的.csv文件。现在我想给用户提供保存该文件所需路径的选项。怎么可能呢。帮助我。

Dim objStreamWriter = New IO.StreamWriter("c:\FaultTypesByMonth.csv")
        Dim Str As String
        Dim i As Integer
        Dim j As Integer       
        Dim headertext1(rsTerms.Columns.Count) As String
        Dim k As Integer = 0
        Dim arrcols As String = Nothing
        For Each column As DataColumn In TempTab.Columns
            headertext1(k) = column.ColumnName
            arrcols += column.ColumnName.ToString() + ","c
            k += 1
        Next

        objStreamWriter.WriteLine(arrcols)
        For i = 0 To (TempTab.Rows.Count - 1)
            For j = 0 To (TempTab.Columns.Count - 1)

                'this IF statement stops it from adding a comma after the last field
                If j = (TempTab.Columns.Count - 1) Then
                    Str = (TempTab.Rows(i)(j).ToString)
                Else
                    Str = (TempTab.Rows(i)(j).ToString & ",")
                End If
                objStreamWriter.Write(Str)
            Next
            objStreamWriter.WriteLine()
        Next
        objStreamWriter.Close()

' After save the file in C:/  I want to save the same file in any other Path for my convenience.
'------------------------------------------------------------------------------------------------

        Dim sd As New SaveFileDialog
        sd.Filter = "CSV Files (*.csv)|*.csv"
        sd.FileName = "FaultTypesByMonth"
        If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
            'save the file here
            Debug.WriteLine("Save file location:" + sd.FileName)
        End If

2 个答案:

答案 0 :(得分:1)

如果是控制台应用程序,您可以从command line读取路径参数。

如果是GUI应用程序,则可以显示保存文件对话框,在WinForms中使用SaveFileDialog class

要将文件保存到不同的位置,请将编写器代码放在以文件路径作为参数的函数中:

 Sub SaveFile(filePath As String)
     Dim objStreamWriter = New IO.StreamWriter(filePath)
     ' ... your code here
 End Sub

 Sub ButtonClick
     SaveFile("c:\FaultTypesByMonth.csv")
     ' ... SaveFileDialog code
     SaveFile(sd.Filename)
 End Sub

要复制文件,请使用File.Copy

 ' ... SaveFileDialog code
 File.Copy("c:\FaultTypesByMonth.csv", sd.Filename)

答案 1 :(得分:0)

使用SaveFileDialog class

简单示例:

Private Sub SaveFile()
    Dim sd As New SaveFileDialog
    sd.Filter = "CSV Files (*.csv)|*.csv"
    If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
        'save the file here
        Debug.WriteLine("Save file location:" + sd.FileName)
    End If
End Sub