imports System.IO
创新互联是一家集策划、设计、技术开发一体的专业网站制作公司,技术团队10年来致力于为客户提供企业网站定制,手机网站制作设计。经过多年发展,公司技术团队,先后服务了近千家客户,包括各类中小企业、上市公司、高校、政府。公司在过去10年的资源积累,追求并一直坚持,为客户打造更有价值的互联网平台。
读取指定文件
'
'读取指定文本文件
Public Function readtext(ByVal path As String)
If path = "" Then
readtext = "操作失败!"
Exit Function
End If
Try
If File.Exists(path) = True Then
Dim fs As New FileStream(path, FileMode.Open)
Dim sr As New StreamReader(fs)
Dim str As String
str = sr.ReadToEnd.ToString
sr.Close()
fs.Close()
readtext = str
Else
readtext = "操作失败!"
End If
Catch ex As Exception
readtext = "操作失败!"
End Try
End Function
'向指定文件写入数据
Public Function writetext(ByVal path As String, ByVal opi As Integer, ByVal msg As String)
If path = "" Then
writetext = "操作失败!"
Exit Function
End If
Dim op As FileMode
Select Case opi
Case 1
op = FileMode.Append
Case 2
op = FileMode.Create
Case Else
op = FileMode.Create
End Select
Try
If File.Exists(path) = True Then
Dim fs As New FileStream(path, op)
Dim sr As New StreamWriter(fs)
sr.WriteLine(msg)
sr.Close()
fs.Close()
writetext = "操作完成!"
Else
writetext = "操作失败!"
End If
Catch ex As Exception
writetext = "操作失败!"
End Try
End Function
楼上的继续忽悠人吧。2,3句搞定的东西弄这么复杂。。。
就是读取服务器文件呀。
微软论坛就有例子。
Imports System
Imports System.IO
Class Test
Public Shared Sub Main()
Try
' 创建一个实例的StreamReader阅读从一个文件。
Dim sr As StreamReader = New StreamReader("TestFile.txt")
Dim line As String
' 阅读并显示线路从文件,直到最后
' 该文件被达成。
Do
line = sr.ReadLine()
Console.WriteLine(Line)
Loop Until line Is Nothing
sr.Close()
Catch E As Exception
' 让用户知道有什么地方出了差错。
Console.WriteLine("The file could not be read:")
Console.WriteLine(E.Message)
End Try
End Sub
End Class
//上面是微软的例子,你可以参考自己改,下面是我改的。
Imports System.IO
Partial Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Using sr As StreamReader = New StreamReader("E:\新建文本文档.txt", Encoding.GetEncoding("gb2312"))
Response.Write(sr.ReadLine())
End Using
End Sub
End Class
已经测试过了,文件路径自己改,支持TXT格式,其他格式自己修改编码
1、新建一个标准的VB EXE工程,只有一个Form,Form上有两个按钮:Command1和Command2。
2、双击Command1添加如下代码
Private Sub Command1_Click()
Dim strFile As String
Dim intFile As Integer
Dim strData As String
strFile = "c:\学生成绩.txt"
intFile = FreeFile
Open strFile For Input As intFile
strData = StrConv(InputB(FileLen(strFile), intFile), vbUnicode)
Debug.Print strData
Close intFile
End Sub
3、按F8开始单步调试代码,点击Command1,进入单步调试功能,
4、多次按下F8或直接按下F5运行完成,就完成了读取文本文件内容并输出到立即窗口。