VB_NET语言操作txt文件代码

合集下载

VB.NET读写文本文件,终于有点明白了

VB.NET读写文本文件,终于有点明白了

读写文本文件,终于有点明白了以前vb6的读写老写错,进入vb2010终于有些明白了。

好,正戏开场:主演: puter.filesystemsystem.io.streamReadersystem.io.streamWriter配角:OpenFileDialogSaveFileDialog剧情一般都是OpenFileDialog或SaveFileDialog跟龙套,提供路径和文件名后,由主演们操作。

先调戏一下,,小演一下:[vb] view plaincopyprint?1.Private Sub Button1_Click(ByVal sender As System.Objec t, ByVal e As System.EventArgs) Handles Button1.Click2.If OpenFileDialog1.showdialog = DialogResult.OK Thenputer.FileSystem.WriteAllText(OpenFileDialog1.Fil eName, TextBox1.T ext, False)4.End If5.End Submy命名空间具有快速访问特性,常见的:puter 当前(本地)计算机硬件、软件、文件信息。

my.application 当前应用程序的信息:标题、目录、版本号。

my.forms 当前项目窗体信息my.resources 应用程序资源的相关信息(只读),允许用户动态获取应用程序的资源。

my.setting 应用程序设置的相关程序。

存储或设置er 当前机器上激活的用户信息my.webservices 当前机器激活的WEB服务信息,也可用于访问新的WEB服务器。

比如: 当前机器上的用户名puter.clock.location 当前机器上的当地日期与时间正式调戏:对于my[vb] view plaincopyprint?puter.FileSystem.ReadAllText(OpenFileDialog1.File Name, System.Text.ASCIIEncoding.Default)puter.FileSystem.WriteAllText(OpenFileDialog1.Fil eName, TextBox1.T ext, False)注1:读时,容易乱码,加上后面参数部分注2:写时false表示不追加,即覆盖式写入。

vb操作txt(VB operation TXT)

vb操作txt(VB operation TXT)

vb操作txt(VB operation TXT)细胞(1,1)代表A1细胞(2,C)代表C2 = COUNTIF(“”)+ COUNTIF(“”)+ COUNTIF(“”)1。

怎么通过代码创建一个文本文件,并读取,更新内容以上为随即方式打开的文本文件昏暗的gfilenum为整数gfilenum = FreeFile随机gfilenum len = 3打开“文件路径及文件名”“以随即方式打开一文件如果文件不存在就新建用得到# gfilenum,记录在文件中位置,要放取得的数据的变量”读取操作用把# gfilenum,记录在文件中位置,要放着要写入数据的变量”写操作近# filenum”关闭文件以下为顺序方式打开的文件昏暗的gfilenum为整数gfilenum = FreeFile打开输出”文件路径及文件名”gfilenum”以写入方式打开文本打印# gfilenum,要写入的文本写#文件号,要写入的文本昏暗的gfilenum为整数gfilenum = FreeFile打开“文件路径及文件名“输入”以读出方式打开文本gfilenum输入# gfilenum,用来放读取的内容的内存变量名还可用线路输入#,等读取更详细的查MSDN()2。

VB读取文本文件时,调用对象中使用报错了文本中去。

如果是集F = fs。

中去(“E:\表格\痕迹。

txt”,读书,真的,TristateUseDefault)出现错误:运行时错误格”:无效的过程调用或参数如果是集F = fs。

中去(“E:\表格\痕迹。

txt)”则不会报错。

用文件对象啊filesystemcontrol操作就好了啊再加上一个文本读取文件第一行就好了啊。

3。

VB通过FileSystemObject,可以读取文本文件(.txt)。

对于。

蝙蝠文件,VB可否直接读取?蝙蝠也属于文本类文件可以读取不用FSO也行:把文本文件内容读取文本框:朦胧的TempFile As Long昏暗的loadbytes()字节tempfile = FreeFile二开文件名作为# tempfileRedim LoadBytes(1~LOF(TempFile))为字节得到# tempfile,,LoadBytes关闭tempfiletext1。

VB.NET文件读写操作

VB.NET文件读写操作

这一部分,你将找到更多常用的文件操作的代码实例。

最常用、最基本的操作就是把text写入文件和读回来。

现在的应用程序通常不用二进制文件作存储简单的变量,而用它来存储对象,对象集合以及其他机器代码。

下面,将看到具体操作的例子。

读写文本文件为了把text保存到文件,创建一个基于FileStream的StreamReader对象,然后调用Write方法把需要保存的text写入文件。

下面的代码用SaveFileDialog 提示用户指定一个文件,用于保存TextBox1的内容。

同样采用类似的语句,我们读取一个文本文件,并把内容显示在TextBox控件中。

StreamReader的ReadToEnd方法返回文件的全部内容。

各种对象的存储采用BinaryFormatte以二进制的形式,或者用SoapFormatter类以XML格式都可以序列化一个具体的对象。

只要把所有BinaryFormatter的引用改为SoapFormatter,无需改变任何代码,就可以以XML格式序列化对象。

首先创建一个BinaryFormatter实例:然后创建一个用于存储序列化对象的FileStream对象:接着调用BinFormatter的Serialize方法序列化任何可以序列化的framework 对象:加一个Serializable属性使得自定义的对象可以序列化下面代码创建一个Person对象实例,然后调用BinFormatter的Serialize方法序列化自定义对象:你也可以在同一个Stream中接着序列化其他对象,然后以同样的顺序读回。

例如,在序列化Person对象之后接着序列化一个Rectangle对象:创建一个BinaryFormatter对象,调用其Deserialize方法,然后把返回的值转化为正确的类型,就是整个反序列化过程。

然后接着发序列化Stream的其他对象。

假定已经序列化了Person和Rectangle两个对象,以同样的顺序,我们反序列化就可以得到原来的对象:大多数程序处理对象集合而不是单个的对象。

VB NET文件操作

VB NET文件操作

知识点1 文件结构
为了有效的对数据进行处理,必须以某种特定的方式 存放数据,这种特定的方式称为文件结构。文件由记 录(Record)组成,一个文件含一个以上的记录,记 录是由一组相关的字段(Field)组成。字段也称域, 由若干字符(Character)组成,用来表示一项数据。 字符是构成文件的最基本单位。字符可以是数字、字 母、特殊符号或单一字节。
件夹下,并改名为VB,语句如下: Directory.Move(“E:\VBNET”,“E:\program\VB”)
GetLogicalDrivers 获取逻辑盘符
该方法功能是返回一个字符串数组,为当前计算机中 所有逻辑驱动器名,每个驱动器名是形如“C:\” 的字符串,格式如下:
Directory.GetLogicalDrivers()
除此之外,可根据存储数据的性质将文件 分为程序文件和数据文件;根据文件的流 向分为输入文件和输出文件;根据文件的Βιβλιοθήκη 存储介质分为磁盘文件、磁带文件等等。
知识点3 文件访问方式
文件访问主要是对文件的读、写操作。 读文件是将文件中的数据读入计算机内存。即向计算机输入数据。 写文件---------将计算机内存中的数据写入文件中。 顺序文件、随机文件以及二进制文件由于文件中记录的组织方式和
无论Directory类还是DirectoryInfo类都是System.IO命 名空间的成员,因此在使用两个类之前,需要先引入 System.IO命名空间。
Directory类提供了文件夹操作的全部方法,由于该类 提供的方法是共享的,所以不需要先建立对象就可以 直接调用它的方法,下面介绍它的常用方法:
GetDirectories 获取文件夹下的子文件夹
GetFiles 获取文件夹下的文件

vb读取txt文件

vb读取txt文件

vb读取txt文件1.怎么通过代码创建一个文本文件,并读取,更新内容以上为随即方式打开的文本文件dim gfilenum as integergfilenum = FreeFileOpen "文件路径及文件名" For Random As gfilenum len=3\'以随即方式打开一文件如果文件不存在就新建用get #gfilenum ,记录在文件中位置,要放取得的数据的变量\'读取操作用put #gfilenum ,记录在文件中位置,要放着要写入数据的变量\'写操作close #filenum\'关闭文件以下为顺序方式打开的文件dim gfilenum as integergfilenum = FreeFileOpen "文件路径及文件名" For output As gfilenum \'以写入方式打开文本print #gfilenum,要写入的文本write #filenum,要写入的文本dim gfilenum as integergfilenum = FreeFileOpen "文件路径及文件名" For input As gfilenum \'以读出方式打开文本input #gfilenum ,用来放读取的内容的内存变量名还可用line input#,input()等读取更详细的查msdn2.VB读取文本文件时,调用TextStream 对象中使用OpenTextFile报错了。

如果是Set f = fs.OpenTextFile("E:\\table\\trace.txt", forreading, True, TristateUseDefault)出现错误:Run-time error \'5\':Invalid procedure call or argument如果是Set f = fs.OpenTextFile("E:\\table\\trace.txt)"则不会报错。

vb.net中文件读写的用法

vb.net中文件读写的用法

是一种基于VB语言的面向对象程序设计语言,它是微软推出的一种用于开发Windows评台应用程序的工具。

在中,文件的读写是非常常见的操作,我们可以通过一些API来实现文件的读写操作。

在本文中,我将介绍如何在中进行文件的读写操作,包括文件的打开、读取、写入和关闭等操作。

希望通过本文的介绍,能够帮助大家更好地掌握中文件读写的用法。

一、文件的打开在中,我们可以使用FileStream类来打开一个文件。

FileStream类是用于提供文件的读写操作的一个类,通过它我们可以打开一个文件,并进行读写操作。

下面是一个打开文件的示例代码:Dim fs As FileStream = New FileStream("C:\test.txt", FileMode.Open)在上面的代码中,我们首先创建了一个FileStream对象,并以"test.txt"为文件名,以FileMode.Open的方式来打开了这个文件。

通过这个代码,我们就可以在中打开一个文件了。

二、文件的读取在中,我们可以使用StreamReader类来进行文件的读取操作。

StreamReader类是用于读取文件内容的一个类,通过它我们可以方便地读取文件的内容。

下面是一个读取文件的示例代码:Dim sr As StreamReader = New StreamReader("C:\test.txt")Dim content As Stringcontent = sr.ReadToEnd()Console.WriteLine(content)在上面的代码中,我们首先创建了一个StreamReader对象,并以"test.txt"为文件名来创建了这个对象。

然后我们通过sr.ReadToEnd()方法来将整个文件的内容读取到content变量中,并最后将content的内容输出到控制台上。

VB.NETVB2010自己动手做记事本源码

VB.NETVB2010自己动手做记事本源码

VB2010自己动手做记事本源码Imports System.IOPublic Class Form1Dim TempPath As StringPrivate Sub打开OToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles打开OToolStripMenuItem.ClickTryOpenFileDialog1.FileName = ""OpenFileDialog1.Filter = "文本文档|*.txt"OpenFileDialog1.InitialDirectory = "C:\"OpenFileDialog1.ShowDialog()TextBox1.Text = File.ReadAllText(OpenFileDialog1.FileName, System.Text.Encoding.Default)TempPath = OpenFileDialog1.FileNameCatch ex As ExceptionMsgBox(ex.Message)End TryEnd SubPrivate Sub保存SToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles保存SToolStripMenuItem.ClickTryFile.WriteAllText(TempPath, TextBox1.Text, System.Text.Encoding.Default) Catch ex As Exception MsgBox(ex.Message)End TryEnd SubPrivate Sub另存为AToolStripMenuItem_Click(ByVal senderAToolStripMenuItem.ClickTrySaveFileDialog1.ShowDialog()Catch ex As ExceptionMsgBox(ex.Message)End TryEnd SubPrivate Sub新建NToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles新建NToolStripMenuItem.Click'TextBox1.Text = ""TextBox1.Clear()End SubPrivate Sub撤消UToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles撤消UToolStripMenuItem.ClickTextBox1.Undo()End SubPrivate Sub重复RToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles重复RToolStripMenuItem.ClickTextBox1.Undo()End SubPrivate Sub剪切TToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles剪切TToolStripMenuItem.ClickTextBox1.Cut()End SubPrivate Sub复制CToolStripMenuItem_Click(ByVal sender AsCToolStripMenuItem.ClickTextBox1.Copy()End SubPrivate Sub粘贴PToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles粘贴PToolStripMenuItem.ClickTextBox1.Paste()End SubPrivate Sub全选AToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles全选AToolStripMenuItem.ClickTextBox1.SelectAll()End SubPrivate Sub自动换行CT oolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles自定义CToolStripMenuItem.ClickIf TextBox1.WordWrap = True ThenTextBox1.WordWrap = FalseElseTextBox1.WordWrap = TrueEnd IfEnd SubPrivate Sub退出XToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles退出XToolStripMenuItem.ClickMe.Close()End SubPrivate Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load End SubEnd Class。

vbnet编码解码例子

vbnet编码解码例子

Imports System.TextImports System.IOImports System.ThreadingPublic Class Form1Dim openFileDialog As OpenFileDialogDim saveFileDialog As SaveFileDialogDim filePath As String = ""Dim byteString As String = ""Dim textString As String = ""Dim bytecode() As ByteDim inputFilePath As String = ""Dim optionList1 As List(Of String)Private Property tempDragPath As StringPrivate Sub ComboBox1_SelectedIndexChanged(ByVal sender AsSystem.Object, ByVal e As System.EventArgs) HandlesComboBox1.SelectedIndexChangedEnd SubPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadControl.CheckForIllegalCrossThreadCalls = False'false为a能¨¹跨?进?程¨¬'Dim fromEncod As Encoding = Encoding.GetEncoding("")' MsgBox()'MsgBox("Form1_Load")btnOpenDialog.Visible = FalseComboBox1.BeginUpdate()ComboBox2.BeginUpdate()'MessageBox.Show(optionArray(0).ToString)' MsgBox("123456")optionList1 = ConvertUtil.getEncodingsFromSystem()Dim i As StringFor Each i In optionList1ComboBox1.Items.Add(i)ComboBox2.Items.Add(i)NextComboBox2.EndUpdate()ComboBox1.EndUpdate()ComboBox1.SelectedIndex = optionList1.Count - 1ComboBox2.SelectedIndex = optionList1.Count - 1End SubPrivate Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.ClickTry'GC.Collect()openFileDialog = New OpenFileDialogopenFileDialog.Filter = "txt files(*.txt)|*.txt|log(*.log)|*.log|All files (*.*)|*.*"If openFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK ThenfilePath = openFileDialog.FileNamefilePathTextBox.Text = filePath'C:\Users\Administrator\Documents\ipmsg.logopenFileDialog.Dispose()'textString = IO.File.ReadAllText(filePath,System.Text.Encoding.GetEncoding("GB2312")) '得Ì?到Ì?文?本À?可¨¦以°?读¨¢取¨?ANSI文?本À?'经-测a算?IO.File.ReadAllText(filePath)只?能¨¹区?分¤?unicode,utf8,不?能¨¹区?分¤?ANSI'MsgBox(textString)' byteTextBox.Text = IO.File.ReadAllText(filePath) '得Ì?到Ì?文?本À?' byteTextBox.Text =IO.File.ReadAllBytes(filePath).ToArray.ToString' byteTextBox.Text =System.Text.Encoding.Default.GetString(IO.File.ReadAllBytes(filePath))textString = IO.File.ReadAllText(filePath)bytecode = IO.File.ReadAllBytes(filePath)'MsgBox("bytecode " + bytecode.Length.ToString + "\r\n" + textString)byteString = BitConverter.ToString(bytecode).Replace("-", " ")byteTextBox.Text = byteString'System.Text.Encoding.Default'Dim str1 As String = System.BitConverter.ToString(System.Text.Encoding.UTF8.Ge tBytes("要°a转Áa换?的Ì?文?字Á?可¨¦以°?是º?任¨?何?数ºy字Á?"))'System.Text.Encoding.Convert()'IO.File.ReadAllBytes("c:/123.txt")' IO.File.ReadAllLines("c:/123.txt")' IO.File.ReadAllText("c:/123.txt")' 上¦?面?是º?读¨¢取¨?()'' IO.File.CreateText("c:/123.txt")' IO.File.WriteAllText("c:/123.txt", "")' IO.File.WriteAllLines("c:/123.txt", New String() {})' IO.File.WriteAllBytes("c:/123.txt", New Byte() {})' 这a几?个?都?可¨¦创ä¡ä建¡§()End IfCatch ex As ExceptionEnd TryEnd SubPrivate Sub filePathText_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles filePathTextBox.MouseDoubleClickTryopenFileDialog = New OpenFileDialogIf openFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK ThenfilePath = openFileDialog.FileNamefilePathTextBox.Text = filePath'C:\Users\Administrator\Documents\ipmsg.logopenFileDialog.Dispose()textString = IO.File.ReadAllText(filePath) '得Ì?到Ì?文?本À?bytecode = IO.File.ReadAllBytes(filePath)byteString = BitConverter.ToString(bytecode).Replace("-", " ")byteTextBox.Text = byteStringEnd IfCatch ex As ExceptionEnd TryEnd SubPrivate Sub filePathTextBox_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles filePathTextBox.KeyUp If e.KeyCode = Keys.Enter Then'MessageBox.Show("filePathTextBox.Enter")inputFilePath = filePathTextBox.Text' Dim s As String = "C:\Users\Administrator\Documents"' If File.Exists(s) Then'MessageBox.Show("文?件t")' ElseIf Directory.Exists(s) Then' MessageBox.Show("路¡¤径?")' Else' MessageBox.Show("什º2么¡ä都?不?是º?")' End IfIf File.Exists(Trim(inputFilePath)) Then'C:\Users\Administrator\Documents\ipmsg.logfilePath = inputFilePathtextString = IO.File.ReadAllText(inputFilePath) '得Ì?到Ì?文?本À?bytecode = IO.File.ReadAllBytes(filePath)byteString = BitConverter.ToString(bytecode).Replace("-", " ")byteTextBox.Text = byteString' Dim tempStr As String' tempStr = UTF8Encoding.Convert(U, )'Encoding.UTF8 .GetBytes ()'Encoding.Unicode.GetBytes("你?的Ì?串ä?")'Encoding.ASCII.GetString()ElseMsgBox("文?件t不?存ä?在¨²,ê?请?重?新?输º?入¨?路¡¤径?!ê?")filePathTextBox.Text = ""End IfEnd IfEnd SubPrivate Sub filePathTextBox_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles filePathTextBox.DragDropDim Files As String() = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())For Each File As String In FilestempDragPath = File' MsgBox("tempDragPath:" + tempDragPath)filePathTextBox.Text = tempDragPathbytecode = IO.File.ReadAllBytes(tempDragPath)byteString = BitConverter.ToString(bytecode).Replace("-", " ")byteTextBox.Text = byteStringNextEnd SubPrivate Sub filePathTextBox_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles filePathTextBox.DragEnter' 確ä_定¡§使º1用®?者?抓Á£¤進M來¨ª的Ì?是º?檔n案ã?If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then' 允¨º許S拖ª?拉¤-動¨®作Á¡Â繼¤^續¤m (這@時r滑?鼠º¨®游®?標?應a該?會t顯@示º? +)e.Effect = DragDropEffects.AllEnd If' MsgBox("filePathTextBox_DragEnter")' If e.Data.GetDataPresent(DataFormats.FileDrop) Then' e.Effect = DragDropEffects.Link' Else' e.Effect = DragDropEffects.None' End IfEnd SubPrivate Sub btnOpenDialog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenDialog.ClickTryDim myThread As New Thread(AddressOf showProgressDialog)myThread.Start()Thread.Sleep(2000)myThread.Abort()Catch ex As ExceptionMsgBox(ex.Message)End TryEnd SubPrivate Sub showProgressDialog()Dim test As testDialog = New testDialog()test.ShowDialog()End SubPrivate Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.ClickDim ComboBox1Text As String = ComboBox1.Text.TrimDim strArray() As String = ComboBox1Text.Split(" ") '将?文?本À?分¤?割?获?取¨?'strArray(0)=""Dim getEncoingText As String = strArray(0).Trim'MsgBox("bytecode: " + bytecode.Length.ToString + ",encoding :" + encoding + "," + textString)'判D断?原-来¤¡ä的Ì?编À¨¤码?Dim bytecode1(bytecode.Length) As Byte' Array.Copy(bytecode, 0, bytecode1, 0, bytecode.Length)If (optionList1.Contains(ComboBox1Text)) ThenIf (bytecode(0) = 255 And bytecode(1) = 254) Or (bytecode(1) = 255 And bytecode(0) = 254) Then'去¨£¤文?件t头ª¡¤Unicode UnicodeBigEndian ff fe,fe ff'MsgBox("Unicode")Dim fromEncod As Encoding = Encoding.Unicode'Array.Copy(bytecode, 2, bytecode1, 0, bytecode.Length - 2)TryDim targetEncod As Encoding =Encoding.GetEncoding(getEncoingText)Dim targetBytes As Byte() = Encoding.Convert(fromEncod, targetEncod, bytecode)DimtargetEncodChars(targetEncod.GetCharCount(targetBytes, 0, targetBytes.Length) - 1) As ChartargetEncod.GetChars(targetBytes, 0, targetBytes.Length, targetEncodChars, 0)Dim targetString As New String(targetEncodChars)decodeTextBox.Text = targetStringCatch ex As ExceptionMsgBox(ex.Message)End TryElseIf bytecode(0) = Convert.ToInt32("EF", 16) And bytecode(1) = Convert.ToInt32("bb", 16) And bytecode(2) = Convert.ToInt32("bf", 16) Then'ef bb bf UTF-8' MsgBox("UTF8")Dim fromEncod As Encoding = Encoding.UTF8'Array.Copy(bytecode, 2, bytecode1, 0, bytecode.Length - 2)TryDim targetEncod As Encoding =Encoding.GetEncoding(getEncoingText)Dim targetBytes As Byte() = Encoding.Convert(fromEncod, targetEncod, bytecode)DimtargetEncodChars(targetEncod.GetCharCount(targetBytes, 0, targetBytes.Length) - 1) As ChartargetEncod.GetChars(targetBytes, 0, targetBytes.Length, targetEncodChars, 0)Dim targetString As New String(targetEncodChars)decodeTextBox.Text = targetStringCatch ex As ExceptionMsgBox(ex.Message)End TryElse' MsgBox("ANSI")Dim fromEncod As Encoding = Encoding.Default 'ANSI'Array.Copy(bytecode, 2, bytecode1, 0, bytecode.Length - 2)TryDim targetEncod As Encoding =Encoding.GetEncoding(getEncoingText)Dim targetBytes As Byte() = Encoding.Convert(fromEncod, targetEncod, bytecode)DimtargetEncodChars(targetEncod.GetCharCount(targetBytes, 0, targetBytes.Length) - 1) As ChartargetEncod.GetChars(targetBytes, 0, targetBytes.Length, targetEncodChars, 0)Dim targetString As New String(targetEncodChars)decodeTextBox.Text = targetStringCatch ex As ExceptionMsgBox(ex.Message)End TryEnd IfElseMsgBox("请?重?新?输º?入¨?!ê?")ComboBox1.Text = ""End IfEnd SubPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click'MsgBox(ComboBox1.Text.Trim + "," + ComboBox2.Text.Trim)Dim ComboBox1Text As String = ComboBox1.Text.TrimDim strArray() As String = ComboBox1Text.Split(" ") '将?文?本À?分¤?割?获?取¨?'strArray(0)=""Dim getEncoingText1 As String = strArray(0).TrimDim ComboBox2Text As String = ComboBox2.Text.TrimstrArray = ComboBox1Text.Split(" ") '将?文?本À?分¤?割?获?取¨?Dim getEncoingText2 As String = strArray(0).Trim'MsgBox("bytecode: " + bytecode.Length.ToString + ",encoding :" + encoding + "," + textString)'判D断?原-来¤¡ä的Ì?编À¨¤码?Dim bytecode1(bytecode.Length) As Byte' Array.Copy(bytecode, 0, bytecode1, 0, bytecode.Length)Dim targetString As StringDim targetEncod As EncodingIf (optionList1.Contains(ComboBox1Text)) And(optionList1.Contains(ComboBox1Text)) ThenDim fromEncod As Encoding =Encoding.GetEncoding(getEncoingText1)TrytargetEncod = Encoding.GetEncoding(getEncoingText2)Dim tempByteCode() As Byte =fromEncod.GetBytes(decodeTextBox.Text)Dim targetBytes As Byte() = Encoding.Convert(fromEncod, targetEncod, tempByteCode)Dim targetEncodChars(targetEncod.GetCharCount(targetBytes, 0, targetBytes.Length) - 1) As ChartargetEncod.GetChars(targetBytes, 0, targetBytes.Length, targetEncodChars, 0)targetString = New String(targetEncodChars)' MsgBox(targetString)Catch ex As ExceptionMsgBox(ex.Message)End TryElseMsgBox("请?重?新?输º?入¨?!ê?")ComboBox2.Text = ""ReturnEnd IfIf String.IsNullOrEmpty(targetString) ThenReturnEnd IfsaveFileDialog = New SaveFileDialogsaveFileDialog.Title = "保À¡ê存ä?文?字Á?"saveFileDialog.Filter = "Test files(*.txt)|*.txt|All Files|*.*"saveFileDialog.AddExtension() = TruesaveFileDialog.CheckPathExists() = TruesaveFileDialog.FilterIndex = 0Dim ioStream As System.IO.StreamIf saveFileDialog.ShowDialog() = DialogResult.OK ThenioStream = saveFileDialog.OpenFileDim SW As New StreamWriter(ioStream, targetEncod)'SNSISystem.Text.Encoding.DefaultIf Not (ioStream Is Nothing) Then'以°?byte形?式º?保À¡ê存ä?' Dim a(10) As Byte' a(0) = &HA4' a(1) = &HB5'创ä¡ä建¡§FileStream对?象¨®' Dim w As New FileStream("D:\00.aa", FileMode.Create)'创ä¡ä建¡§BinaryWriter对?象¨®' Dim b_Write As BinaryWriter = New BinaryWriter(w)' b_Write.Write(a(0))' b_Write.Write(a(1))' b_Write.Close()' w.Close()SW.Write(targetString)'puter.FileSystem.WriteAllBytes("D:\00.aa", a, True) 'true为a添¬¨ª加¨®方¤?式º?End IfSW.Close()ioStream.Close()End IfEnd SubEnd ClassImports SystemImports System.TextImports Microsoft.VisualBasicPublic Class ConvertUtilPublic Shared Sub convertByteCode(ByVal fromEncoding As String, ByVal targetEncoding As String, ByVal src() As Byte)Dim fromEncod As Encoding =Encoding.GetEncoding(fromEncoding.Trim)Dim targetEncod As Encoding =Encoding.GetEncoding(targetEncoding.Trim)Dim unicodeString As String = "This string contains the unicode character Pi(" & ChrW(&H3A0) & ")"' Create two different encodings.Dim ascii As Encoding = Encoding.ASCIIDim [unicode] As Encoding = Encoding.Unicode' Convert the string into a byte[].Dim unicodeBytes As Byte() = [unicode].GetBytes(unicodeString)' Perform the conversion from one encoding to the other.Dim asciiBytes As Byte() = Encoding.Convert([unicode], ascii, unicodeBytes)' Convert the new byte[] into a char[] and then into a string.' This is a slightly different approach to converting to illustrate' the use of GetCharCount/GetChars.Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length) - 1) As Charascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)Dim asciiString As New String(asciiChars)' Display the strings created before and after the conversion.Console.WriteLine("Original string: {0}", unicodeString)Console.WriteLine("Ascii converted string: {0}", asciiString) End SubPublic Shared Function getEncodingsFromSystem() As List(Of String) ' For every encoding, compare the name properties with .' Display only the encodings that have one or more different names.Dim ei As EncodingInfoDim encodingList As New List(Of String)For Each ei In Encoding.GetEncodings()Dim e As Encoding = ei.GetEncoding()encodingList.Add(e.BodyName + " " + e.EncodingName) Next eiReturn encodingListEnd FunctionPublic Shared Function byteCodeToString(ByVal targetEncoding As String, ByVal src() As Byte) As StringDim targetEncod As Encoding =Encoding.GetEncoding(targetEncoding.Trim)Dim byteCode() As Byte'If byteCode (0)=Return targetEncod.GetString(src)End FunctionEnd Class。

[VB.NET]文件操作

[VB.NET]文件操作

[]文件操作文件操作实例说明在本实例中,我们制作一个能够对文件进行操作的应用程序。

程序运行后,可以新建一个文件和删除一个文件;同时可以显示文件的属性如文件类型、建立时间、更改时间和访问时间等。

还可以更改这些属性。

程序运行结果如图89-1所示。

图89-1 运行结果<script type="text/javascript" src="/pagead/show_ads.js"> </script>技术要点l 新建和删除文件l 获得文件属性l 更改文件属性实现过程■ 新建项目打开Visual ,选择"新建项目",在项目类型窗口中选择"Visual Basic项目",在模板窗口中选择"Windows应用程序",在名称域中输入"FileOperate",然后选择保存路径。

单击"确认"。

■ 添加控件在窗体上添加六个Button控件,一个GroupBox控件,并在GroupBox控件上放置八个Label控件。

■ 更改属性将说明性的Label控件和Button控件的Text属性设置为和界面一致。

其余属性保持不变。

■ 添加代码Dim fileexam As System.IO.File'新建文件Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.ClickIf fileexam.Exists("c:/abc.txt") = True ThenMsgBox("这个文件已经存在了!")Exit SubEnd Iffileexam.Create("c:/abc.txt")MsgBox("成功建立文件!")Button3.Enabled = TrueEnd Sub'删除文件Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.ClickIf fileexam.Exists("c:/abc.txt") = True Thenfileexam.Delete("c:/abc.txt")MsgBox("成功删除文件!")Button3.Enabled = FalseElseMsgBox("这个文件不存在")End IfEnd Sub'得到文件的相关信息Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.ClickLabel1.Text = fileexam.GetAttributes("c:/abc.txt").ToStringLabel2.Text = fileexam.GetCreationTime("c:/abc.txt").ToStringLabel3.Text = fileexam.GetLastWriteTime("c:/abc.txt").ToStringLabel4.Text = fileexam.GetLastAccessTime("c:/abc.txt").ToStringEnd Sub'更改文件的属性(只读、隐藏、系统或文档)Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Clickfileexam.SetAttributes("c:/abc.txt",IO.FileAttributes.ReadOnly)End Sub'更改文件的建立时间Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Clickfileexam.SetCreationTime("c:/abc.txt", Now)End Sub'更改最后访问时间Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Clickfileexam.SetLastAccessTime("c:/abc.txt", Now)End Sub■ 运行程序单击菜单"调试|启动"或单击图标运行程序。

【免费下载】VB打开txt文件

【免费下载】VB打开txt文件
方法二: 先声明一字符串变量,然后用空格填充字符串,使变量大小与文件大小一致, 再通过 Get 语句将文件全部数据存储到变量中,从而达到获取整个文件字节数 的目的。此法可以打开大于 32K 的文件,但应该注意的是,装载文件的容器必 须能装载大于 32K 的文件,下例用 RichTextBox 控件显示打开的文件:Private Sub Command1_Click() Dim sA As String Open "f:\d.txt" For Binary As #1 sA = Space(LOF(1)) '用空格填充 sA 变量 N,] j WQ y0Get #1, , sA '用 Get 语句获取文件全部内容 RichTextBox1.Text = sA Close #1 End Sub
方法二: 先声明一字符串变量,然后用空格填充字符串,使变量大小与文件大小一致,再通过 Get 语句将文件全部数据存储到变量中, 从而达到获取整个文件字节数的目的。此法可以打开大于 32K 的文件,但应该注意的是,装载文件的容器必须能装载大于 32K 的文件,下例用 RichTextBox 控件显示打开的文件:Private Sub Command1_Click() Dim sA As String Open "f:\d.txt" For Binary As #1 sA = Space(LOF(1)) '用空格填充 sA 变量 N,] j WQ y0Get #1, , sA '用 Get 语句获取文件全部内容 RichTextBox1.Text = sA Close #1 End Sub
打开文本文件是不少程序必须处理的问题。如何更有效地打开文本文件应该是 一个值得研究的课题。为此,笔者将自己搜集到的几种方法无私地奉献出来(_-),供各位参考。同时期盼大家也来参与,借 VB 编程乐园这块宝地互相交流。 如您有这份心,土人在这里先说声谢谢! 下面所举的例子均假设 F 盘下有一个名为 d.txt 的文本文件,若需要尝试这些 例子请作相应的改动。

VBNET操作word文档代码

VBNET操作word文档代码

操作WORD(VBA)操作WORD1Public Class WordOpLib234 Private oWordApplic As Word.ApplicationClass5 Private oDocument As Word.Document6 Private oRange As Word.Range7 Private oShape As Word.Shape8 Private oSelection As Word.Selection91011 Public Sub New()12 '激活com word接口13 oWordApplic = New Word.ApplicationClass14 oWordApplic.Visible = False1516 End Sub17 '设置选定文本18 Public Sub SetRange(ByVal para As Integer)19 oRange = oDocument.Paragraphs(para).Range20 oRange.Select()21 End Sub22 Public Sub SetRange(ByVal para As Integer, ByVal sent As Integer)23 oRange = oDocument.Paragraphs(para).Range.Sentences(sent)24 oRange.Select()25 End Sub26 Public Sub SetRange(ByVal startpoint As Integer, ByVal endpoint As Integer, ByVal flag As Boolean)27 If flag = True Then28 oRange = oDocument.Range(startpoint, endpoint)29 oRange.Select()30 Else3132 End If33 End Sub3435 '生成空的新文档36 Public Sub NewDocument()37 Dim missing = System.Reflection.Missing.Value38 Dim isVisible As Boolean = True39 oDocument = oWordApplic.Documents.Add(missing, missing, missing, missing)40 oDocument.Activate()41 End Sub42 '使用模板生成新文档43 Public Sub NewDocWithModel(ByVal FileName As String)44 Dim missing = System.Reflection.Missing.Value45 Dim isVisible As Boolean = False46 Dim strName As String47 strName = FileName48 oDocument = oWordApplic.Documents.Add(strName, missing, missing, isVisible)49 oDocument.Activate()50 End Sub51 '打开已有文档52 Public Sub OpenFile(ByVal FileName As String)53 Dim strName As String54 Dim isReadOnly As Boolean55 Dim isVisible As Boolean56 Dim missing = System.Reflection.Missing.Value5758 strName = FileName59 isReadOnly = False60 isVisible = True6162 oDocument = oWordApplic.Documents.Open(strName, missing, isReadOnly, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing, missing)63 oDocument.Activate()6465 End Sub66 Public Sub OpenFile(ByVal FileName As String, ByVal isReadOnly As Boolean)67 Dim strName As String68 Dim isVisible As Boolean69 Dim missing = System.Reflection.Missing.Value7071 strName = FileName72 isVisible = True7374 oDocument = oWordApplic.Documents.Open(strName, missing, isReadOnly, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing, missing)75 oDocument.Activate()76 End Sub77 '退出Word78 Public Sub Quit()79 Dim missing = System.Reflection.Missing.Value80 oWordApplic.Quit()81 System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApplic)82 oWordApplic = Nothing83 End Sub84 '关闭所有打开的文档85 Public Sub CloseAllDocuments()86 oWordApplic.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)87 End Sub88 '关闭当前的文档89 Public Sub CloseCurrentDocument()9091 oDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)92 End Sub93 '保存当前文档94 Public Sub Save()95 Try96 oDocument.Save()97 Catch98 MsgBox(Err.Description)99 End Try100 End Sub101 '另存为文档102 Public Sub SaveAs(ByVal FileName As String)103 Dim strName As String104 Dim missing = System.Reflection.Missing.Value105106 strName = FileName107108 oDocument.SaveAs(strName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)109 End Sub110 '保存为Html文件111 Public Sub SaveAsHtml(ByVal FileName As String)112 Dim missing = System.Reflection.Missing.Value113 Dim strName As String114115 strName = FileName116 Dim format = CInt(Word.WdSaveFormat.wdFormatHTML)117118 oDocument.SaveAs(strName, format, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)119 End Sub120 '插入文本121 Public Sub InsertText(ByVal text As String)122 oWordApplic.Selection.TypeText(text)123 End Sub124 '插入一个空行125 Public Sub InsertLineBreak()126 oWordApplic.Selection.TypeParagraph()127 End Sub128 '插入指定行数的空行129 Public Sub InsertLineBreak(ByVal lines As Integer)130 Dim i As Integer131 For i = 1 To lines132 oWordApplic.Selection.TypeParagraph()133 Next134 End Sub135 '插入表格136 Public Sub InsertTable(ByRef table As DataTable)137 Dim oTable As Word.Table138 Dim rowIndex, colIndex, NumRows, NumColumns As Integer139 rowIndex = 1140 colIndex = 0141 If (table.Rows.Count = 0) Then142 Exit Sub143 End If144145 NumRows = table.Rows.Count + 1146 NumColumns = table.Columns.Count147 oTable = oDocument.Tables.Add(oWordApplic.Selection.Range(), NumRows, NumColumns)148149150 '初始化列151 Dim Row As DataRow152 Dim Col As DataColumn153 'For Each Col In table.Columns154 ' colIndex = colIndex + 1155 ' oTable.Cell(1, colIndex).Range.InsertAfter(Col.ColumnName)156 'Next157158 '将行添入表格159 For Each Row In table.Rows160 rowIndex = rowIndex + 1161 colIndex = 0162 For Each Col In table.Columns163 colIndex = colIndex + 1164 oTable.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))165 Next166 Next167 oTable.Rows(1).Delete()168 oTable.AllowAutoFit = True169 oTable.ApplyStyleFirstColumn = True170 oTable.ApplyStyleHeadingRows = True171172 End Sub173 '插入表格(修改为在原有表格的基础上添加数据)174 Public Sub InsertTable2(ByRef table As DataTable, ByVal strbmerge As String, ByVal totalrow As Integer)175 Dim oTable As Word.Table176 Dim rowIndex, colIndex, NumRows, NumColumns As Integer177 Dim strm() As String178 Dim i As Integer179 rowIndex = 1180 colIndex = 0181182 If (table.Rows.Count = 0) Then183 Exit Sub184 End If185186 NumRows = table.Rows.Count + 1187 NumColumns = table.Columns.Count188 'oTable = oDocument.Tables.Add(oWordApplic.Selection.Range(), NumRows, NumColumns)189190191 '初始化列192 Dim Row As DataRow193 Dim Col As DataColumn194 'For Each Col In table.Columns195 ' colIndex = colIndex + 1196 ' oTable.Cell(1, colIndex).Range.InsertAfter(Col.ColumnName)197 'Next198199 '将行添入表格200 For Each Row In table.Rows201 colIndex = 0202 GotoRightCell()203 oWordApplic.Selection.InsertRows(1)204 For Each Col In table.Columns205 GotoRightCell()206 colIndex = colIndex + 1207 Try208 oWordApplic.Selection.TypeText(Row(Col.ColumnName))209 Catch ex As Exception210 oWordApplic.Selection.TypeText(" ")211 End Try212 'oWordApplic.Selection.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))213 Next214 Next215 '如果strbmerge不为空.则要合并相应的行和列216 If strbmerge.Trim().Length <> 0 Then217 strm = strbmerge.Split(";")218 For i = 1 To strm.Length - 1219 If strm(i).Split(",").Length = 2 Then220 MergeDouble(totalrow, strm(0), strm(i).Split(",")(1), strm(i).Split(",")(0))221 End If222 MergeSingle(totalrow, strm(0), strm(i))223 Next224 End If225 '删除可能多余的一行226 'GotoRightCell()227 'GotoDownCell()228 'oWordApplic.Selection.Rows.Delete()229 'oTable.AllowAutoFit = True230 'oTable.ApplyStyleFirstColumn = True231 'oTable.ApplyStyleHeadingRows = True232 End Sub233 '插入表格(专门适应工程结算工程量清单)234 Public Sub InsertTableQD(ByRef table As DataTable, ByRef table1 As DataTable)235 Dim oTable As Word.Table236 Dim rowIndex, colIndex, NumRows, NumColumns As Integer237 Dim xmmc As String238 Dim i As Integer239 Dim j As Integer240 rowIndex = 1241 colIndex = 0242243 If (table.Rows.Count = 0) Then244 Exit Sub245 End If246247 NumRows = table.Rows.Count + 1248 NumColumns = table.Columns.Count249 'oTable = oDocument.Tables.Add(oWordApplic.Selection.Range(), NumRows,NumColumns)250251252 '初始化列253 Dim Row As DataRow254 Dim rowtemp As DataRow255 Dim row1() As DataRow256 Dim Col As DataColumn257 Dim coltemp As DataColumn258 'For Each Col In table.Columns259 ' colIndex = colIndex + 1260 ' oTable.Cell(1, colIndex).Range.InsertAfter(Col.ColumnName)261 'Next262263 '将行添入表格264 For Each Row In table.Rows265 colIndex = 0266 xmmc = Row("项目名称")267 GotoRightCell()268 oWordApplic.Selection.InsertRows(1)269 For Each Col In table.Columns270 GotoRightCell()271 Try272 If (Col.ColumnName = "项目序号") Then273oWordApplic.Selection.TypeText(intToUpint(Val(Row(Col.ColumnName))))274 Else275 oWordApplic.Selection.TypeText(Row(Col.ColumnName))276 End If277 Catch ex As Exception278 oWordApplic.Selection.TypeText(" ")279 End Try280 'oWordApplic.Selection.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))281 Next282 row1 = table1.Select("项目名称='" + xmmc + "'")283284 For i = 0 To row1.Length - 1285 GotoRightCell()286 oWordApplic.Selection.InsertRows(1)287 For j = 0 To table1.Columns.Count - 1288 If (table1.Columns(j).ColumnName <> "项目名称") Then289 GotoRightCell()290 Try291 oWordApplic.Selection.TypeText(row1(i)(j))292 Catch ex As Exception293 oWordApplic.Selection.TypeText(" ")294 End Try295 End If296 'oWordApplic.Selection.Cell(rowIndex, colIndex).Range.InsertAfter(Row(Col.ColumnName))297 Next298 Next299300301302 Next303 '删除可能多余的一行304 'GotoRightCell()305 'GotoDownCell()306 'oWordApplic.Selection.Rows.Delete()307 'oTable.AllowAutoFit = True308 'oTable.ApplyStyleFirstColumn = True309 'oTable.ApplyStyleHeadingRows = True310 End Sub311 '插入表格,为了满足要求,在中间添加一根竖线312 Public Sub InsertTable3(ByRef table As DataTable, ByVal introw As Integer, ByVal intcol As Integer)313 Dim rowIndex, colIndex, NumRows, NumColumns As Integer314 Dim Row As DataRow315 Dim Col As DataColumn316 If (table.Rows.Count = 0) Then317 Exit Sub318 End If319 '首先是拆分选中的单元格320 oDocument.Tables(1).Cell(introw, 3).Split(table.Rows.Count, 2)321 '选中初始的单元格322 oDocument.Tables(1).Cell(introw, 3).Select()323 '将行添入表格324 For Each Row In table.Rows325 Try326 oDocument.Tables(1).Cell(introw, 3).Range.InsertAfter(Row(0))327 oDocument.Tables(1).Cell(introw, 4).Range.InsertAfter(Row(1))328 Catch ex As Exception329 oDocument.Tables(1).Cell(introw, 3).Range.InsertAfter(" ")330 oDocument.Tables(1).Cell(introw, 4).Range.InsertAfter(" ")331 End Try332 introw = introw + 1333 Next334 End Sub335 '设置对齐336 Public Sub SetAlignment(ByVal strType As String)337 Select Case strType338 Case "center"339 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter340 Case "left"341 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft342 Case "right"343 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight344 Case "justify"345 oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify346 End Select347 End Sub348 '设置字体349 Public Sub SetStyle(ByVal strFont As String)350 Select Case strFont351 Case "bold"352 oWordApplic.Selection.Font.Bold = 1353 Case "italic"354 oWordApplic.Selection.Font.Italic = 1355 Case "underlined"356 oWordApplic.Selection.Font.Subscript = 1357 End Select358 End Sub359 '取消字体风格360 Public Sub DissableStyle()361 oWordApplic.Selection.Font.Bold = 0362 oWordApplic.Selection.Font.Italic = 0363 oWordApplic.Selection.Font.Subscript = 0364 End Sub365 '设置字体字号366 Public Sub SetFontSize(ByVal nSize As Integer)367 oWordApplic.Selection.Font.Size = nSize368 End Sub369 '跳过本页370 Public Sub InsertPageBreak()371 Dim pBreak As Integer372 pBreak = CInt(Word.WdBreakType.wdPageBreak)373 oWordApplic.Selection.InsertBreak(pBreak)374 End Sub375 '转到书签376 Public Sub GotoBookMark(ByVal strBookMark As String)377 Dim missing = System.Reflection.Missing.Value378 Dim BookMark = CInt(Word.WdGoToItem.wdGoToBookmark)379 oWordApplic.Selection.GoTo(BookMark, missing, missing, strBookMark)380 End Sub381 '判断书签是否存在382 Public Function BookMarkExist(ByVal strBookMark As String) As Boolean383 Dim Exist As Boolean384 Exist = oDocument.Bookmarks.Exists(strBookMark)385 Return Exist386 End Function387 '替换书签的内容388 Public Sub ReplaceBookMark(ByVal icurnum As String, ByVal strcontent As String) 389 strcontent = strcontent.Replace("0:00:00", "")390 oDocument.Bookmarks(icurnum).Select()391 oWordApplic.Selection.TypeText(strcontent)392 End Sub393394 '得到书签的名称395 Public Function GetBookMark(ByVal icurnum As String, ByRef bo As Boolean) As String 396 Dim strReturn As String397 If Right(oDocument.Bookmarks(icurnum).Name, 5) = "TABLE" Then398 bo = True399 Dim strTemp As String400 strTemp = oDocument.Bookmarks(icurnum).Name()401 strReturn = Mid(strTemp, 1, Len(strTemp) - 5)402 Else403 bo = False404 strReturn = oDocument.Bookmarks(icurnum).Name405 End If406 Return strReturn407 End Function408 '得到书签的名称409 Public Function GetBookMark1(ByVal icurnum As String) As String410 Return oDocument.Bookmarks(icurnum).Name411 End Function412 '转到文档结尾413 Public Sub GotoTheEnd()414 Dim missing = System.Reflection.Missing.Value415 Dim unit = Word.WdUnits.wdStory416 oWordApplic.Selection.EndKey(unit, missing)417 End Sub418 '转到文档开头419 Public Sub GotoTheBegining()420 Dim missing = System.Reflection.Missing.Value421 Dim unit = Word.WdUnits.wdStory422 oWordApplic.Selection.HomeKey(unit, missing)423 End Sub424 '删除多余的一行425 Public Sub DelUnuseRow()426 oWordApplic.Selection.Rows.Delete()427 End Sub428 '转到表格429 Public Sub GotoTheTable(ByVal ntable As Integer)430 'Dim missing = System.Reflection.Missing.Value431 'Dim what = Word.WdGoToItem.wdGoToTable432 'Dim which = Word.WdGoToDirection.wdGoToFirst433 'Dim count = ntable434435 'oWordApplic.Selection.GoTo(what, which, count, missing)436 'oWordApplic.Selection.ClearFormatting()437438 'oWordApplic.Selection.Text = ""439 oRange = oDocument.Tables(ntable).Cell(1, 1).Range440 oRange.Select()441442 End Sub443 '转到表格的某个单元格444 Public Sub GotoTableCell(ByVal ntable As Integer, ByVal nRow As Integer, ByVal nColumn As Integer)445 oRange = oDocument.Tables(ntable).Cell(nRow, nColumn).Range446 oRange.Select()447 End Sub448 '表格中转到右面的单元格449 Public Sub GotoRightCell()450 Dim missing = System.Reflection.Missing.Value451 Dim direction = Word.WdUnits.wdCell452 oWordApplic.Selection.MoveRight(direction, missing, missing)453 End Sub454 '表格中转到左面的单元格455 Public Sub GotoLeftCell()456 Dim missing = System.Reflection.Missing.Value457 Dim direction = Word.WdUnits.wdCell458 oWordApplic.Selection.MoveLeft(direction, missing, missing)459 End Sub460 '表格中转到下面的单元格461 Public Sub GotoDownCell()462 Dim missing = System.Reflection.Missing.Value463 Dim direction = Word.WdUnits.wdCell464 oWordApplic.Selection.MoveDown(direction, missing, missing)465 End Sub466 '表格中转到上面的单元格467 Public Sub GotoUpCell()468 Dim missing = System.Reflection.Missing.Value469 Dim direction = Word.WdUnits.wdCell470 oWordApplic.Selection.MoveUp(direction, missing, missing)471 End Sub472 '文档中所有的书签总数473 Public Function TotalBkM() As Integer474 Return oDocument.Bookmarks.Count475 End Function476 '选中书签477 Public Sub SelectBkMk(ByVal strName As String)478 oDocument.Bookmarks.Item(strName).Select()479 End Sub480 '插入图片481 Public Sub InsertPic(ByVal FileName As String)482 Dim missing = System.Reflection.Missing.Value483 oWordApplic.Selection.InlineShapes.AddPicture(FileName, False, True, missing).Select()484 oShape = oWordApplic.Selection.InlineShapes(1).ConvertToShape485 oWordApplic.Selection.WholeStory()486 oShape.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoSendBehindText)487 End Sub488 '统一调整图片的位置.也就是往上面调整图片一半的高度489 Public Sub SetCurPicHei()490 Dim e As Word.Shape491 For Each e In oDocument.Shapes492 oDocument.Shapes().Select()493 oWordApplic.Selection.ShapeRange.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage494 oWordApplic.Selection.ShapeRange.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionParagraph495 oWordApplic.Selection.ShapeRange.LockAnchor = True496'oWordApplic.Selection.ShapeRange.IncrementTop(oDocument.Shapes().Height)497 Next498 End Sub499500 Public Sub SetCurPicHei1()501 Dim e As Word.Shape502 For Each e In oDocument.Shapes503 oDocument.Shapes().Select()504oWordApplic.Selection.ShapeRange.IncrementTop(oDocument.Shapes().Height / 2)505 Next506 End Sub507 Public Sub SetCurPicHei2()508 Dim e As Word.Shape509 For Each e In oDocument.Shapes510 oDocument.Shapes().Select()511oWordApplic.Selection.ShapeRange.IncrementTop(-oDocument.Shapes().Height / 2)512 Next513 End Sub514 Public Function intToUpint(ByVal a As Integer) As String515 Dim result As String = "一百"516 Dim a1, a2 As Integer517 Dim strs() As String = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"} 518 If (a <= 10) Then519 result = strs(a)520 ElseIf (a < 100) Then521 a1 = a / 10522 a2 = a Mod 10523 If (a = 1) Then524 result = "十" + strs(a2)525 End If526 Else527 result = strs(a1) + "十" + strs(a2)528 End If529 Return result530 End Function531 '合并没有参照的某一列,一般来讲对应第一列532 'itotalrow 总行数533 'initrow 初始开始的行数,一般情况下该值不为0,没有标题栏的一般为0534 'intcol 列数535 Public Sub MergeSingle(ByVal itotalrow As Integer, ByVal initrow As Integer, ByVal intcol As Integer)536 oDocument.Tables(1).Cell(initrow + 1, intcol).Select()537 Dim irow As Integer '当前行数538 Dim strValue As String '循环比较的行初值539 Dim i As Integer540 Dim direction = Word.WdUnits.wdLine541 Dim extend = Word.WdMovementType.wdExtend542543 i = 0544 irow = 1 + initrow '初始值为1545 For i = 2 + initrow To itotalrow + initrow546547 strValue = oDocument.Tables(1).Cell(irow, intcol).Range.Text548 If (oDocument.Tables(1).Cell(i, intcol).Range.Text = oDocument.Tables(1).Cell(irow, intcol).Range.Text) Then549 '这是对最后一次处理的特殊情况.550 If (i = itotalrow + initrow) Then551 oWordApplic.Selection.MoveDown(direction, (i - irow), extend)552 If (i - irow >= 1) Then553 oWordApplic.Selection.Cells.Merge()554 End If555 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue556 End If557 Else558 oWordApplic.Selection.MoveDown(direction, (i - irow - 1), extend)559 If (i - irow - 1 >= 1) Then560 oWordApplic.Selection.Cells.Merge()561 End If562 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue563 irow = i564 oDocument.Tables(1).Cell(irow, intcol).Select()565 End If566 Next i567 End Sub568 '合并有参照的某一列569 'itotalrow 总行数570 'initrow 初始开始的行数,一般情况下该值不为0,没有标题栏的一般为0571 'intcol 列数572 'basecol 参照合并的那一列573 Public Sub MergeDouble(ByVal itotalrow As Integer, ByVal initrow As Integer, ByVal intcol As Integer, ByVal basecol As Integer)574 oDocument.Tables(1).Cell(initrow + 1, intcol).Select()575 Dim irow As Integer '当前行数576 Dim strValue As String '循环比较的行初值577 Dim i As Integer578 Dim direction = Word.WdUnits.wdLine579 Dim extend = Word.WdMovementType.wdExtend580581 i = 0582 irow = 1 + initrow '初始值为1583 For i = 2 + initrow To itotalrow + initrow584585 strValue = oDocument.Tables(1).Cell(irow, intcol).Range.Text586 If (oDocument.Tables(1).Cell(i, intcol).Range.Text = oDocument.Tables(1).Cell(irow, intcol).Range.Text) And (getdata(i, basecol) = getdata(irow, basecol)) Then587 '这是对最后一次处理的特殊情况.588 If (i = itotalrow + initrow) Then589 oWordApplic.Selection.MoveDown(direction, (i - irow), extend)590 If (i - irow >= 1) Then591 oWordApplic.Selection.Cells.Merge()592 End If593 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue594 End If595 Else596 oWordApplic.Selection.MoveDown(direction, (i - irow - 1), extend)597 If (i - irow - 1 >= 1) Then598 oWordApplic.Selection.Cells.Merge()599 End If600 oDocument.Tables(1).Cell(irow, intcol).Range.Text = strValue601 irow = i602 oDocument.Tables(1).Cell(irow, intcol).Select()603 End If604 Next i605 End Sub606 '得到某个单元的值,如果为空的话,有两种情况.607 '其一:是一个合并的单元格,取其上面的值608 '其二:该单元格本来就是空值609 Public Function getdata(ByVal introw As Integer, ByVal intcol As Integer) As String610 Try611 If (oDocument.Tables(1).Cell(introw, intcol).Range.Text = "" Or (oDocument.Tables(1).Cell(introw, intcol).Range.Text = Nothing)) Then612 getdata = getdata(introw - 1, intcol)613 Else614 getdata = oDocument.Tables(1).Cell(introw, intcol).Range.Text615 End If616 Catch ex As Exception617 getdata = getdata(introw - 1, intcol)618 End Try619620621 End Function622End Class要想作为一个优秀的编程人员,不得不每天都进行学习,来增加自己的知识库,以免被技术所淘汰。

VB操作TXT

VB操作TXT

cells‎(1,1)‎代表A1‎ cel‎l(2,"‎C")代表‎C2,=C‎O UNTI‎F("")‎+COUN‎T IF("‎")+CO‎U NTIF‎("") ‎1.怎么‎通过代码创‎建一个文本‎文件,并读‎取,更新内‎容以上为‎随即方式打‎开的文本文‎件dim‎gfil‎e num ‎a s in‎t eger‎gfil‎e num ‎= Fre‎e File‎Open‎ "文件‎路径及文件‎名" Fo‎r Ran‎d om A‎s gfi‎l enum‎len=‎3\'以‎随即方式打‎开一文件如‎果文件不存‎在就新建‎用get ‎#gfil‎e num ‎,记录在文‎件中位置,‎要放取得的‎数据的变量‎\'读取操‎作用pu‎t #gf‎i lenu‎m ,记录‎在文件中位‎置,要放着‎要写入数据‎的变量\'‎写操作c‎l ose ‎#file‎n um\'‎关闭文件‎以下为顺序‎方式打开的‎文件di‎m gfi‎l enum‎as i‎n tege‎rgfi‎l enum‎= Fr‎e eFil‎eOpe‎n "文‎件路径及文‎件名" F‎o r ou‎t put ‎A s gf‎i lenu‎m \'以‎写入方式打‎开文本p‎r int ‎#gfil‎e num,‎要写入的文‎本wri‎t e #f‎i lenu‎m ber,‎要写入的文‎本di‎m gfi‎l enum‎as i‎n tege‎rgfi‎l enum‎= Fr‎e eFil‎eOpe‎n "文‎件路径及文‎件名" F‎o r in‎p ut A‎s gfi‎l enum‎\'以读‎出方式打开‎文本in‎p ut #‎g file‎n um ,‎用来放读取‎的内容的内‎存变量名‎还可用li‎n e in‎p ut#,‎i nput‎()等读取‎更详细的查‎m sdn‎2.VB‎读取文本文‎件时,调用‎T extS‎t ream‎对象中使‎用Open‎T extF‎i le报错‎了。

VB.NET常用技巧代码

VB.NET常用技巧代码

1.单元格相互计算关键字:.FocusedPrivate Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChangedIf TextBox1.Focused ThenTextBox2.Text = Val(TextBox1.Text) * 3ElseIf TextBox2.Focused ThenTextBox1.Text = Val(TextBox2.Text) / 3End IfEnd Sub2.对比两个数据的字符大小关键字:StrComp(string1,string2)Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Label4.Text = StrComp(TextBox5.Text, TextBox6.Text)'string1 < string2,返回-1'string1 = string2,返回0'string1 > string2,返回1End Sub3.对应匹配关键字:While….End WhilePrivate Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click Dim city() As String = {"北京", "上海", "天津", "广州", "哈尔滨", "长春", "沈阳", "西安", "兰州", "银川", "太原"}Dim no() As String= {"010", "021", "022", "020", "0451", "0431", "024", "029", "0931", "0951", "0351"} Dim i% = 0While (i < UBound(no) And StrComp(no(i), TextBox7.Text) <> 0)i = i + 1End WhileIf StrComp(no(i), TextBox7.Text) = 0 ThenLabel5.Text = "对应城市为:" & city(i)ElseLabel5.Text = "没有所对应城市"End IfEnd Sub4.随机数生成、在原基础扩增数组、逐行扩增文本显示关键字:Int(Rnd() * 80) + 20、ReDim Preserve score(n + 1)、mystr = mystr + String(i) & Chr(13) & Chr(10)Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click Dim n%, score!(), i%, sum!Dim mystr As String = ""n = Val(TextBox8.Text)ReDim score(n - 1)For i = 0 To n - 1score(i) = Int(Rnd() * 80) + 20sum = sum + score(i)NextReDim Preserve score(n + 1)score(n) = sum / n 'score(n)平均数计算,score(n+1)计算超过平均数的个数For i = 0 To n - 1If score(i) > score(n) Thenscore(n + 1) = score(n + 1) + 1End IfNextFor i = 0 To n - 1mystr = mystr + Str(score(i)) & Chr(13) & Chr(10)NextTextBox9.Text = mystrTextBox10.Text = score(n)TextBox11.Text = score(n + 1)End Sub5.骗过文本框TextChanged事件关键字:Dim a#a = Val(TextBox1.Text)TextBox1.Text = ""TextBox1.Text = a6.LinkLabel单击后文字切换关键字:定义全局变量、NotDim judge As BooleanPrivate Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e AsSystem.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClickedjudge = Not judgeIf judge = False ThenLinkLabel1.Text = "温度/℃"ElseLinkLabel1.Text = "温度/℉"End IfEnd Sub7.限制文本框数字输入关键字:KeyPress事件、CType(转换类型)、InStr(字符查找)、TextBox1.SelectionStart=0(光标在起始位置)Private Sub T11_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles T11.KeyPress, T12.KeyPress, T13.KeyPressDim bool0 As Boolean, bool1 As Boolean, bool2 As Boolean, bool3 As Boolean'对输入的小数点进行判断If InStr(CType(sender, TextBox).Text, ".") > 0 Thenbool0 = True' 如果已经输入了一个小数点,则第二个小数点不能再输入ElseIf CType(sender, TextBox).Text Like"*e" = True Or CType(sender, TextBox).Text Like"*e*" = True ThenIf CType(sender, TextBox).SelectionStart >= InStr(CType(sender, TextBox).Text, "e") Thenbool0 = True' 如果没有输入小数点,当出现如“1e”字符时,则光标从“e”往后不能输入小数点;如果出现如“1e32”,则“e”后面的不能输入小数点ElseIf Mid(CType(sender, TextBox).Text, 1, 1) = "-"ThenIf CType(sender, TextBox).SelectionStart = 0 Thenbool0 = True'如果有负号,则负号前不能输入小数点End IfEnd IfElseIf Mid(CType(sender, TextBox).Text, 1, 1) = "-"ThenIf CType(sender, TextBox).SelectionStart = 0 Thenbool0 = True'如果有负号,则负号前不能输入小数点End IfElsebool0 = FalseEnd If'对输入e进行判断If InStr(CType(sender, TextBox).Text, "e") > 0 Thenbool1 = True'如果已经输入一个e,则第二个e不能再输入ElseIf CType(sender, TextBox).Text = ""Thenbool1 = True'如果文本框为空值,则不能以e打头ElseIf CType(sender, TextBox).Text = "."Or CType(sender, TextBox).Text = "-."Or CType(sender, TextBox).Text = "-"Thenbool1 = True'如果文本框第一个字符为小数点、负号、“-.”,则不能紧接着输入e ElseIf CType(sender, TextBox).Text Like"*"ThenIf CType(sender, TextBox).SelectionStart <> Len(CType(sender, TextBox).Text) Thenbool1 = True'如果文本框已经有字符,则只有当光标在字符串最右侧时可以输入e End IfElsebool1 = FalseEnd If'对负号输入判断If CType(sender, TextBox).Text = ""Thenbool2 = True'如果文本框为空值,则可以输入负号ElseIf CType(sender, TextBox).Text Like"*e" = True ThenIf CType(sender, TextBox).SelectionStart = InStr(CType(sender, TextBox).Text, "e") Thenbool2 = True'如果文本框当前字符如“1e”,紧接着可以输入负号ElseIf CType(sender, TextBox).SelectionStart = 0 And Mid(CType(sender, TextBox).Text, 1, 1) <> "-" Thenbool2 = True'如果文本框当前字符如“1e”,光标在起始位置并且第一个字符不是负号时,可以在起始位置输入负号End IfElseIf CType(sender, TextBox).Text Like"*e#*" = True ThenIf CType(sender, TextBox).SelectionStart = InStr(CType(sender, TextBox).Text, "e") Thenbool2 = True'如果文本框当前字符如“1e3”,则当光标移到e后面才能输入负号ElseIf CType(sender, TextBox).SelectionStart = 0 And Mid(CType(sender, TextBox).Text, 1, 1) <> "-" Thenbool2 = True'如果文本框当前字符如“1e3”,光标在起始位置并且第一个字符不是负号时,可以在起始位置输入负号End IfElseIf Mid(CType(sender, TextBox).Text, 1, 1) <> "-"ThenIf CType(sender, TextBox).SelectionStart = 0 Thenbool2 = True'如果文本框当前第一个字符不是负号,则当光标移动到起始位置时可以输入负号End IfElsebool2 = FalseEnd If'对已经输入内容的部分再次输入数字进行判断If InStr(CType(sender, TextBox).Text, "-") > 0 ThenIf CType(sender, TextBox).SelectionStart = 0 Or CType(sender, TextBox).SelectionStart = InStr(2, CType(sender, TextBox).Text, "-") - 1 Thenbool3 = True'两种情况,一种是负号在前面部分,则负号前不能输入数字;另一种是负号在e后面,负号前不能输入数字End IfElsebool3 = FalseEnd If'KeyPress事件的核心部分,对文本框仅限制输入数字、小数点、负号、退格键、e,并通过以上的判断来具体体现限制字符输入If Char.IsDigit(e.KeyChar) Or e.KeyChar = "."Or e.KeyChar = Chr(8) Or e.KeyChar = "e"Then If e.KeyChar = "."And bool0 Thene.Handled = TrueElseIf e.KeyChar = "e"And bool1 Thene.Handled = TrueElseIf Char.IsDigit(e.KeyChar) And bool3 Thene.Handled = TrueElsee.Handled = FalseEnd IfElseIf e.KeyChar = "-"And bool2 Thene.Handled = FalseElsee.Handled = TrueEnd IfEnd Sub8.小数位处理关键字:Format()、递归调用'该函数为格式化数字显示格式函数。

VB.NET读写文本文件

VB.NET读写文本文件

读写文本文件***把程序执行错误追加到错误日志中使巧巧读书网的编辑能够读取错误日志记得以前使用vb 的时候对文本文件的操作挺麻烦的特别是在写文件的时候需要区分什么顺序文件随机文件很教材都专门针对文本文件的读写开辟了一个章节来讲解够麻烦的了现在使用 net读写文本文件因为时间仓促没来得及细看MSDN 同时受到的思路影响把问题复杂化了在追加记录到文本文件尾部的时候就写不下去了后来仔细看了一下MSDN中例子问题终于得到了解决好了下面进入正题分别把中对文本文件进行读和写的通用操作做个示例免得后来新手多走弯路我们这里是对文件流进行操作所以模块前面要加上Imports System IO写操作使用System IO的StreamWriter 下面是代码Dim strFilePath As String = SaveFileDialog FileNameDim sw As StreamWriter = New StreamWriter(strFilePath True) true是指以追加的方式打开指定文件For i = To jtemp = i ToStringsw WriteLine(temp)sw Flush()Nextsw Close()sw = Nothing首先要说明的是构造函数newPublic Sub New(path append Encoding)path 要打开文件的完整路径如果文件不存在则自动建立一个新的文件append 缺省值为false 指示是否以追加方式打开指定文件false——如果存在path指定的文件则覆蓋原文件否则建立一个新文件 true——如果存在path指定的文件则打开该文件以追加数据的方式在文尾写数据否则建立一个新文件Encoding 缺省值为System Text Encoding Default 即使用系统缺省的编码指示以什么样的编码写文件WriterLine(str)在文本中添加一个新行同时在行尾加上回车换行符读操作Dim line As StringDim sr As StreamReader = New StreamReader(strPath System Text Encoding Default)Do While sr Peek() >line = sr ReadLine()Loopsr Close()sr = Nothing构造函数newPublic Sub New(Path Encoding)path 要打开文件的完整路径如果文件抛出一个错误Encoding 缺省值为System Text Encoding Default 即使用系统缺省的编码指示以什么样的编码读文件lishixinzhi/Article/program/net/201311/11973。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

做二次开发过程中的一些代码搜集和个人的试错及注释:
Dim str_File_1 As String = puter.FileSystem.ReadAllText("E:\Visual Studio\Visual Basic\GUI\WindowsApplication2\Resources\1.tcl", System.Text.Encoding.ASCII) '根据实际的编码读第一个文件
Dim str_File_2 As String = puter.FileSystem.ReadAllText("E:\Visual Studio\Visual Basic\GUI\WindowsApplication2\Resources\2.tcl", System.Text.Encoding.ASCII) '根据实际的编码读第二个文件
FileOpen(1, "E:\Visual Studio\Visual Basic\GUI\WindowsApplication2\Resources\1.tcl", OpenMode.Input, OpenAccess.Default, OpenShare.Shared) '以读方式打开文件
FileOpen(2, "E:\Visual Studio\Visual Basic\GUI\WindowsApplication2\Resources\2.tcl", OpenMode.Output, OpenAccess.Default, OpenShare.Shared) '以写方式打开文件
Print(2, str_File_1) '将1文件写入2中
FileClose(1)
FileClose(2)
Imports System.IO
Public Class TXTClass
'为了能够操作txt文本文档,需要在类的前面加入“System.IO”空间的引用;
'然后定义3个变量sw(用于write操作,变量类型StreamWriter)、
'sr(用于read操作,变量类型StreamReader)、
'strRead()(用于保存从文本文档中读入的数据,变量类型String数组);
'然后写一个空的sub New()过程(类必须有的)。

Private swAsStreamWriter
Private srAsStreamReader
Public strRead() As String
Public Sub New()
End Sub
'写操作
'写入一行数据到文本文件
'以追加的形式写入一行数据
Public Sub ZhuiJiaSingle(ByValParth As String, ByValstrline As String)
sw = New StreamWriter(Parth, True, System.Text.Encoding.Default)
sw.WriteLine(strline)
sw.Flush()
sw.Close()
sw = Nothing
End Sub
'以覆盖的形式写入一行数据
Public Sub FuGaiSingle(ByValParth As String, ByValstrline As String) sw = New StreamWriter(Parth, False, System.Text.Encoding.Default)
sw.WriteLine(strline)
sw.Flush()
sw.Close()
sw = Nothing
End Sub
'写入多行数据到文本文件
'以追加的形式写入多行数据
Public Sub ZhuiJiaDuoHang(ByValParth As String, ByValstr() As String) Dim iAs Integer
sw = New StreamWriter(Parth, True, System.Text.Encoding.Default) For i = 0 Tostr.Length - 1
sw.WriteLine(str(i))
sw.Flush()
Next
sw.Close()
sw = Nothing
End Sub
'以覆盖的形式写入多行数据
Public Sub FuGaiDuoHang(ByValParth As String, ByValstr() As String) Dim iAs Integer
sw = New StreamWriter(Parth, False, System.Text.Encoding.Default) For i = 0 Tostr.Length - 1
sw.WriteLine(str(i))
sw.Flush()
Next
sw.Close()
sw = Nothing
End Sub
'读操作
Public Function DuWenBen(ByValParth As String)
Dim iAs Integer = 0
Dim s As String
strRead = Nothing
sr = New StreamReader(Parth, System.Text.Encoding.Default)
Do While sr.Peek() <> -1
s = sr.ReadLine()
ReDim Preserve strRead(i)
i = i + 1
Loop
sr.Close()
sr = Nothing
If i = 0 Then
ReDim Preserve strRead(0)
strRead(0) = "null"
Return strRead
Else
Return strRead
End If
End Function
'删除文本文档的某一行内容
Public Sub deleteonerow(ByValParth As String, ByValRowindex As Integer) Static strNew() As String
Dim iAs Integer = 0
Dim s As String
sr = New StreamReader(Parth, System.Text.Encoding.Default)
Do While sr.Peek() <> -1
s = sr.ReadLine()
If i<>Rowindex Then
ReDim Preserve strNew(i)
strNew(i) = s
i = i + 1
End If
Loop
sr.Close()
FuGaiDuoHang(Parth, strNew)
strNew = Nothing
End Sub
End Class
错误1“Public Sub New(s As String)”的参数太多。

相关文档
最新文档