[英]How to add Text at the end of each line vb.net
I'm developing a program with VB.NET (2013), which works with a local database (sql server 2008 R2), The program is converting database tables into text files , so how to add some text after the last field of each row at the end of each line in that text file, Thanks, And sorry for my english 我正在使用VB.NET(2013)开发一个程序,该程序可与本地数据库(SQL Server 2008 R2)一起使用,该程序将数据库表转换为文本文件,因此如何在每行的最后一个字段之后添加一些文本在该文本文件中每行的末尾,谢谢,对不起我的英语
If mytable.HasRows Then
Dim outputStream As StreamWriter = New StreamWriter(FileName & "table.txt", True, GetEncoding)
Dim row As Integer = 0
myConnection.open()
Do While mytable.Read
Dim header As Integer = 0
Dim counter As Integer = 0
Dim fieldCount As Integer = mytable.FieldCount - 1
While counter <= fieldCount
If counter = 0 Then
outputStream.Write("None ," )
End If
If counter = 3 Then
outputStream.Write("123456 ," )
End If
If counter = 7 Then
outputStream.Write("None ," )
End If
If counter <> fieldCount Then
outputStream.Write(mytable(counter).ToString() & ",")
Else
outputStream.WriteLine(mytable(counter).ToString())
End If
counter += 1
End While
row += 1
Loop
mytable.Close()
outputStream.Close()
myConnection.Close()
End If
Using the example you have provided, you could replace 使用您提供的示例,您可以替换
If counter <> fieldCount Then
outputStream.Write(mytable(counter).ToString() & ",")
Else
outputStream.WriteLine(mytable(counter).ToString())
End If
With: 带有:
If counter <> fieldCount Then
outputStream.Write(mytable(counter).ToString() & ",")
Else
outputStream.WriteLine(mytable(counter).ToString() & "What ever you want to write")
End If
Here's a refactor of the code with your question answered: 这是代码的重构,可以回答您的问题:
Imports System.Data.SqlClient
Imports System.Data
Public Class Class1
Public Sub Writefile()
Dim ConnectionString As String = ""
Using cnn As New SqlConnection(ConnectionString)
cnn.Open()
Using cmd As SqlCommand = cnn.CreateCommand
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "SELECT * FROM SomeTable"
Using da As New SqlDataAdapter
Using ds As New DataSet
da.Fill(ds)
Using sw As New System.IO.StreamWriter("C:\myfile.txt")
For Each r As DataRow In ds.Tables(0).Rows
Dim output As New System.Text.StringBuilder
For c As Integer = 0 To ds.Tables(0).Columns.Count - 1
Select Case c
Case 0
output.Append("none ,")
Case 3
output.Append("123456 ,")
Case 7
output.Append("none ,")
Case Else
output.Append(r(c).ToString)
If c < ds.Tables(0).Columns.Count - 1 Then
output.Append(",")
End If
End Select
sw.WriteLine(output.ToString)
Next
Next
End Using
End Using
End Using
End Using
End Using
End Sub
End Class
This sample includes the database call as well. 此示例还包括数据库调用。 The "Using" blocks will ensure that your objects are disposed and closed appropriately, as well.
“使用”块还可以确保正确放置和关闭对象。 I use this pattern and patterns like it all the time for writing text files.
我一直使用这种模式和类似的模式来编写文本文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.