如何在 VB.NET 中读取 EBCDIC 文件
本文演示了如何在 VB.NET 中读取 EBCDIC 文件,将其转换为 ASCII 并将其写入文件。
引言
弄清楚如何读取 EBCDIC 文件并将其转换为 ASCII 可能会有些棘手。 但是现在,多亏了 .NET,您不必担心头痛或失眠之夜了!
背景
我之所以想写这篇文章,是因为我被要求将 50 多个 VB6 项目升级到 VB.NET 2008。 其中 7 个正在升级的 VB6 项目处理 EBCDIC 文件。 用于翻译这些文件的 VB6 方法非常糟糕! 我尝试了 .NET 的文件编码,并弄清楚了如何非常轻松地翻译 EBCDIC 文件!
Using the Code
这是将文件从 EBCDIC 转换为 ASCII 的完整源代码。 它只有一个函数,可以调用并传递 2 个参数:EBCDIC 文件路径和将创建并加载翻译内容的新的 ASCII 文件路径。
''' <summary>
''' Translates a file from EBCDIC to ASCII.
''' </summary>
''' <param name="sourceEbcdicFilePath">The full path of the EBCDIC file.</param>
''' <param name="newAsciiFilePath">The full path of the new ASCII file
''' that will be created.</param>
''' <remarks></remarks>
Private Sub TranslateFile(ByVal sourceEbcdicFilePath As String, _
ByVal newAsciiFilePath As String)
'Set the encoding to the EBCDIC code page.
Dim encoding As System.Text.Encoding = _
System.Text.Encoding.GetEncoding(37)
'Set this to the length of an EBCDIC line or block.
Dim lineLength As Integer = 134
'Buffer used to store characters read in from the statement input file.
Dim buffer(lineLength - 1) As Char
'Open the EBCDIC file for reading using the EBCDIC encoding.
Dim reader As New IO.StreamReader(sourceEbcdicFilePath, encoding)
'Open a file to write out the data to.
Dim writer As New IO.StreamWriter(newAsciiFilePath, _
False, System.Text.Encoding.Default)
'This is a string to store the translated line.
Dim strAscii As String = String.Empty
'This variable increments every time a block of data is read
Dim iLoops As Integer = 0
'Loop through the EBCDIC file.
Do Until reader.EndOfStream = True
'Read in a block of data from the EBCDIC file.
reader.ReadBlock(buffer, 0, lineLength)
'Translate the string using the EBCDIC encoding.
strAscii = encoding.GetString(encoding.GetBytes(buffer))
'Write the translated string out to a file.
writer.WriteLine(strAscii)
'Only call DoEvents every 1000 loops (increases performance)
iLoops += 1
If iLoops = 1000 Then
Application.DoEvents()
iLoops = 0 'reset
End If
Loop
'Close files.
reader.Close()
writer.Close()
'Release resources.
reader.Dispose()
writer.Dispose()
End Sub
结论
读取 EBCDIC 文件变得很容易! 希望对您也有帮助!
主要记住的是创建 EBCDIC 编码,并在打开 EBCDIC 文件进行读取以及转换 string
时使用它。
祝您翻译愉快!
VBRocks。
历史
- 2008 年 12 月 13 日:初始发布