vb.net 编写固定宽度的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18218557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a fixed-width text file
提问by Caben
I'm writing an app that creates a fixed-width text file. What I've already written works just fine, but I'm wondering if there is a more efficient method. (By efficient, I mean executes faster, not uses less code.)
我正在编写一个创建固定宽度文本文件的应用程序。我已经写的工作得很好,但我想知道是否有更有效的方法。(高效,我的意思是执行速度更快,而不是使用更少的代码。)
Here is the function I've created that pads or trims strings to the required length:
这是我创建的将字符串填充或修剪到所需长度的函数:
Private Function ToLen(ByRef strLen As String, ByRef intLen As Integer) As String
Dim L As Integer = Len(strLen)
If L < intLen Then
Return strLen & Strings.Space(intLen - L)
ElseIf L = intLen Then
Return strLen
Else
Return Strings.Left(strLen, intLen)
End If
End Function
Here is a simplified version of the code that calls it:
这是调用它的代码的简化版本:
Using MyFile1 As New StreamWriter("C:\Temp\MyFile.txt")
Do
' loop through records
MyFile1.WriteLine(ToLen(Item1, 10) & ToLen(Item2, 50) & ToLen(Item3, 25))
Loop
End Using
回答by Steven Doggart
I would recommend using the new .NET methods for string manipulation rather than the old-style VB6 functions, for instance:
我建议使用新的 .NET 方法进行字符串操作,而不是旧式的 VB6 函数,例如:
Private Function ToLen(text As String, length As Integer)
If text.Length > length Then
Return text.SubString(0, length)
Else
Return text.PadRight(length)
End If
End Function
Then, when you are writing to the file, don't concatenate the strings together. It would be more efficient to call Writemultiple times:
然后,当您写入文件时,不要将字符串连接在一起。Write多次调用会更有效:
Using MyFile1 As New StreamWriter("C:\Temp\MyFile.txt")
Do
' loop through records
MyFile1.Write(ToLen(Item1, 10))
MyFile1.Write(ToLen(Item2, 50))
MyFile1.WriteLine(ToLen(Item3, 25))
Loop
End Using

![vb.net Windows XP 上的错误 [IM002] [Microsoft][ODBC 驱动程序管理器]](/res/img/loading.gif)