【问题标题】:Write/Read external files with custom extensions in VBscript在 VBscript 中写入/读取具有自定义扩展名的外部文件
【发布时间】:2009-06-20 03:04:27
【问题描述】:

您如何使用 VBscript 写入或读取具有自定义扩展名的外部文件(例如,可以使用 .cyc 代替 .txt 扩展名)?

我不知道怎么做,而且似乎无法弄清楚。对于读取文件,是否可以只读取文件的一部分?例如,如果我有一行

string1=你好世界!

在我的文件内部,我的脚本如何仅从 string1 行读取以及如何将文本值分配给 vbscript 文件中的字符串?

那么,如何将单个值写入我的文件?

为了澄清,我基本上是在尝试使用外部文件作为配置/数据文件。

这可能是一个非常愚蠢的问题,如果是,我真的很抱歉。

编辑:这是一个两部分的问题,我需要知道上面指定的读写文件的代码,以及如何使用自定义扩展。

【问题讨论】:

    标签: vbscript file-extension


    【解决方案1】:

    如果您想在随机位置读取和写入文本文件,最好的办法是使用 INI 文件。

    INI 文件包含如下所示的条目:

    [owner]
    name=John Doe
    organization=Acme Products
    

    要读取 ini 文件,您需要一个可以这样调用的函数:

    Dim s as string
    s=ReadINI("c:\myfolder\myfile.ext", "owner", "name")
    

    ...这会将“John Doe”放在 s 中。

    执行此操作的代码在这里: http://cwashington.netreach.net/depo/view.asp?Index=553

    编写 INI 文件的工作方式相同。

    这是另一个例子:

    WriteINI("c:\myfolder\myfile.ext", "MySection", "MyItem", "MyValue")
    

    创建一个如下所示的 INI 文件:

    [MySection]
    MyItem=MyValue
    

    您可以根据需要在每个部分中包含任意数量的不同部分和项目。要检索所需的值,您只需使用要检索的值的部分名称和项名称调用 ReadINI。

    【讨论】:

    • 这听起来像是我正在寻找的东西,但是有没有办法从不同的扩展中获得类似的功能?
    • 扩展? .EXT 可以是您想要的任何东西。 [owner] 中的字符串可以是任何你想要的。名称和组织由您决定,值也是如此。
    • 好的,所以我可以使用我想要的任何扩展名,但是否将其视为 INI 文件?谢谢!这解决了我的问题,我假设 WriteINI 是写函数? [所有者] 声明了什么,我如何证明它已到达此声明的末尾并进入下一个声明?
    • 只需为您要声明的每个项目和值调用WriteINI。写入值的顺序无关紧要。
    • 好的,谢谢。有没有办法声明一个节的结尾,还是在声明下一个节时它自己终止?
    【解决方案2】:

    您所要做的就是在文件名末尾包含扩展名,如下所示:

    c:\myfolder\myfile.ext
    

    当您打开文件进行写入时。

    下面是一些示例代码,用于打开一个新文件,向其中写入一行文本,然后关闭该文件:

    Set myFSO = CreateObject("Scripting.FileSystemObject")
    Set WriteStuff = myFSO.OpenTextFile("c:\myfolder\myfile.ext", 2, true)
    WriteStuff.WriteLine("Hello World.")
    WriteStuff.Close
    Set WriteStuff = nothing
    Set myFSO = nothing
    

    这里是读取它的代码:

    Dim S as String
    Set myFSO = CreateObject("Scripting.FileSystemObject")
    Set ReadStuff = myFSO.OpenTextFile("c:\myfolder\myfile.ext", 1)
    S=Readstuff.ReadLine
    ReadStuff.Close
    Set ReadStuff = nothing
    Set myFSO = nothing
    

    http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/other/textfiles/ 有更多示例

    【讨论】:

    • 但是我首先要如何打开文件进行写入呢?这真的是一个由两部分组成的问题。
    • 好的,谢谢你的代码。你能解释一下参数的作用吗? 2 和 True 有什么作用?
    • 2 表示打开一个新文件进行写入。我不确定 true 是什么,但它在 Microsoft 的示例中。
    • 它从第一行读取,如果再次执行Readline则从下一行读取,依此类推。有关更多示例,请参阅activexperts.com/activmonitor/windowsmanagement/adminscripts/…
    • 好的,但是有什么方法可以从特定的行号读取它,比如第三行之类的吗?写作也一样。
    【解决方案3】:

    以下类从 VB.Net 读写 INI 文件:

    Class INI
    
    #Region "API Calls"
        ' standard API declarations for INI access
        ' changing only "As Long" to "As Int32" (As Integer would work also)
        Private Declare Unicode Function WritePrivateProfileString Lib "kernel32" _
        Alias "WritePrivateProfileStringW" (ByVal lpApplicationName As String, _
        ByVal lpKeyName As String, ByVal lpString As String, _
        ByVal lpFileName As String) As Int32
    
        Private Declare Unicode Function GetPrivateProfileString Lib "kernel32" _
        Alias "GetPrivateProfileStringW" (ByVal lpApplicationName As String, _
        ByVal lpKeyName As String, ByVal lpDefault As String, _
        ByVal lpReturnedString As String, ByVal nSize As Int32, _
        ByVal lpFileName As String) As Int32
    #End Region
    
        Public Overloads Function INIRead(ByVal INIPath As String, _
        ByVal SectionName As String, ByVal KeyName As String, _
        ByVal DefaultValue As String) As String
            ' primary version of call gets single value given all parameters
            Dim n As Int32
            Dim sData As String
            sData = space$(1024) ' allocate some room 
            n = GetPrivateProfileString(SectionName, KeyName, DefaultValue, _
            sData, sData.Length, INIPath)
            If n > 0 Then ' return whatever it gave us
                INIRead = sdata.Substring(0, n)
            Else
                iniread = ""
            End If
        End Function
    
    #Region "INIRead Overloads"
        Public Overloads Function INIRead(ByVal INIPath As String, _
        ByVal SectionName As String, ByVal KeyName As String) As String
            ' overload 1 assumes zero-length default
            Return INIRead(inipath, sectionname, KeyName, "")
        End Function
    
        Public Overloads Function INIRead(ByVal INIPath As String, _
        ByVal SectionName As String) As String
            ' overload 2 returns all keys in a given section of the given file
            Return INIRead(inipath, sectionname, Nothing, "")
        End Function
    
        Public Overloads Function INIRead(ByVal INIPath As String) As String
            ' overload 3 returns all section names given just path
            Return INIRead(inipath, Nothing, Nothing, "")
        End Function
    #End Region
    
        Public Sub INIWrite(ByVal INIPath As String, ByVal SectionName As String, _
        ByVal KeyName As String, ByVal TheValue As String)
            Call WritePrivateProfileString(SectionName, KeyName, TheValue, INIPath)
        End Sub
    
        Public Overloads Sub INIDelete(ByVal INIPath As String, ByVal SectionName As String, _
        ByVal KeyName As String) ' delete single line from section
            Call WritePrivateProfileString(SectionName, KeyName, Nothing, INIPath)
        End Sub
    
        Public Overloads Sub INIDelete(ByVal INIPath As String, ByVal SectionName As String)
            ' delete section from INI file
            Call WritePrivateProfileString(SectionName, Nothing, Nothing, INIPath)
        End Sub
    
    End Class
    

    【讨论】:

    【解决方案4】:

    旋风:

    1. 创建文件夹 c:\testarea。
    2. 在刚刚创建的文件夹中创建一个名为 test.vbs 的文本文件,并将下面的代码粘贴到其中。
    3. 双击 test.vbs 文件以执行它。请注意,它会在同一目录中创建一个 test.ini 文件。打开 test.ini 并查看它。

    此代码已经过测试,所以我知道它可以工作。我从http://www.robvanderwoude.com/vbstech_files_ini.php得到它

          Function ReadIni( myFilePath, mySection, myKey )
        ' This function returns a value read from an INI file
        '
        ' Arguments:
        ' myFilePath  [string]  the (path and) file name of the INI file
        ' mySection   [string]  the section in the INI file to be searched
        ' myKey       [string]  the key whose value is to be returned
        '
        ' Returns:
        ' the [string] value for the specified key in the specified section
        '
        ' CAVEAT:     Will return a space if key exists but value is blank
        '
        ' Written by Keith Lacelle
        ' Modified by Denis St-Pierre and Rob van der Woude
    
        Const ForReading   = 1
        Const ForWriting   = 2
        Const ForAppending = 8
    
        Dim intEqualPos
        Dim objFSO, objIniFile
        Dim strFilePath, strKey, strLeftString, strLine, strSection
    
        Set objFSO = CreateObject( "Scripting.FileSystemObject" )
    
        ReadIni     = ""
        strFilePath = Trim( myFilePath )
        strSection  = Trim( mySection )
        strKey      = Trim( myKey )
    
        If objFSO.FileExists( strFilePath ) Then
            Set objIniFile = objFSO.OpenTextFile( strFilePath, ForReading, False )
            Do While objIniFile.AtEndOfStream = False
                strLine = Trim( objIniFile.ReadLine )
    
                ' Check if section is found in the current line
                If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then
                    strLine = Trim( objIniFile.ReadLine )
    
                    ' Parse lines until the next section is reached
                    Do While Left( strLine, 1 ) <> "["
                        ' Find position of equal sign in the line
                        intEqualPos = InStr( 1, strLine, "=", 1 )
                        If intEqualPos > 0 Then
                            strLeftString = Trim( Left( strLine, intEqualPos - 1 ) )
                            ' Check if item is found in the current line
                            If LCase( strLeftString ) = LCase( strKey ) Then
                                ReadIni = Trim( Mid( strLine, intEqualPos + 1 ) )
                                ' In case the item exists but value is blank
                                If ReadIni = "" Then
                                    ReadIni = " "
                                End If
                                ' Abort loop when item is found
                                Exit Do
                            End If
                        End If
    
                        ' Abort if the end of the INI file is reached
                        If objIniFile.AtEndOfStream Then Exit Do
    
                        ' Continue with next line
                        strLine = Trim( objIniFile.ReadLine )
                    Loop
                Exit Do
                End If
            Loop
            objIniFile.Close
        Else
            WScript.Echo strFilePath & " doesn't exists. Exiting..."
            Wscript.Quit 1
        End If
        End Function
    
    
        Sub WriteIni( myFilePath, mySection, myKey, myValue )
        ' This subroutine writes a value to an INI file
        '
        ' Arguments:
        ' myFilePath  [string]  the (path and) file name of the INI file
        ' mySection   [string]  the section in the INI file to be searched
        ' myKey       [string]  the key whose value is to be written
        ' myValue     [string]  the value to be written (myKey will be
        '                       deleted if myValue is <DELETE_THIS_VALUE>)
        '
        ' Returns:
        ' N/A
        '
        ' CAVEAT:     WriteIni function needs ReadIni function to run
        '
        ' Written by Keith Lacelle
        ' Modified by Denis St-Pierre, Johan Pol and Rob van der Woude
    
        Const ForReading   = 1
        Const ForWriting   = 2
        Const ForAppending = 8
    
        Dim blnInSection, blnKeyExists, blnSectionExists, blnWritten
        Dim intEqualPos
        Dim objFSO, objNewIni, objOrgIni, wshShell
        Dim strFilePath, strFolderPath, strKey, strLeftString
        Dim strLine, strSection, strTempDir, strTempFile, strValue
    
        strFilePath = Trim( myFilePath )
        strSection  = Trim( mySection )
        strKey      = Trim( myKey )
        strValue    = Trim( myValue )
    
        Set objFSO   = CreateObject( "Scripting.FileSystemObject" )
        Set wshShell = CreateObject( "WScript.Shell" )
    
        strTempDir  = wshShell.ExpandEnvironmentStrings( "%TEMP%" )
        strTempFile = objFSO.BuildPath( strTempDir, objFSO.GetTempName )
    
        Set objOrgIni = objFSO.OpenTextFile( strFilePath, ForReading, True )
        Set objNewIni = objFSO.CreateTextFile( strTempFile, False, False )
    
        blnInSection     = False
        blnSectionExists = False
        ' Check if the specified key already exists
        blnKeyExists     = ( ReadIni( strFilePath, strSection, strKey ) <> "" )
        blnWritten       = False
    
        ' Check if path to INI file exists, quit if not
        strFolderPath = Mid( strFilePath, 1, InStrRev( strFilePath, "\" ) )
        If Not objFSO.FolderExists ( strFolderPath ) Then
            WScript.Echo "Error: WriteIni failed, folder path (" _
                       & strFolderPath & ") to ini file " _
                       & strFilePath & " not found!"
            Set objOrgIni = Nothing
            Set objNewIni = Nothing
            Set objFSO    = Nothing
            WScript.Quit 1
        End If
    
        While objOrgIni.AtEndOfStream = False
            strLine = Trim( objOrgIni.ReadLine )
            If blnWritten = False Then
                If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then
                    blnSectionExists = True
                    blnInSection = True
                ElseIf InStr( strLine, "[" ) = 1 Then
                    blnInSection = False
                End If
            End If
    
            If blnInSection Then
                If blnKeyExists Then
                    intEqualPos = InStr( 1, strLine, "=", vbTextCompare )
                    If intEqualPos > 0 Then
                        strLeftString = Trim( Left( strLine, intEqualPos - 1 ) )
                        If LCase( strLeftString ) = LCase( strKey ) Then
                            ' Only write the key if the value isn't empty
                            ' Modification by Johan Pol
                            If strValue <> "<DELETE_THIS_VALUE>" Then
                                objNewIni.WriteLine strKey & "=" & strValue
                            End If
                            blnWritten   = True
                            blnInSection = False
                        End If
                    End If
                    If Not blnWritten Then
                        objNewIni.WriteLine strLine
                    End If
                Else
                    objNewIni.WriteLine strLine
                        ' Only write the key if the value isn't empty
                        ' Modification by Johan Pol
                        If strValue <> "<DELETE_THIS_VALUE>" Then
                            objNewIni.WriteLine strKey & "=" & strValue
                        End If
                    blnWritten   = True
                    blnInSection = False
                End If
            Else
                objNewIni.WriteLine strLine
            End If
        Wend
    
        If blnSectionExists = False Then ' section doesn't exist
            objNewIni.WriteLine
            objNewIni.WriteLine "[" & strSection & "]"
                ' Only write the key if the value isn't empty
                ' Modification by Johan Pol
                If strValue <> "<DELETE_THIS_VALUE>" Then
                    objNewIni.WriteLine strKey & "=" & strValue
                End If
        End If
    
        objOrgIni.Close
        objNewIni.Close
    
        ' Delete old INI file
        objFSO.DeleteFile strFilePath, True
        ' Rename new INI file
        objFSO.MoveFile strTempFile, strFilePath
    
        Set objOrgIni = Nothing
        Set objNewIni = Nothing
        Set objFSO    = Nothing
        Set wshShell  = Nothing
        End Sub
             '
             '
        Call  WriteINI("c:\testarea\Test.INI","Section1","Item1","Value1")
        Call  WriteINI("c:\testarea\Test.INI","Section1","Item2","Value2")
        Call  WriteINI("c:\testarea\Test.INI","Section1","Item3","Value3")
        Call  WriteINI("c:\testarea\Test.INI","Section2","Item4","Value4")
        Call  WriteINI("c:\testarea\Test.INI","Section2","Item5","Value5")
    

    【讨论】:

    • 啊,一个应用程序。您的应用程序是什么样的?它真的是完全用 vbscript 编写的吗?因为如果不是这样,可能会有更好的方法来做到这一点。
    • 它是一个“Windows 窗体应用程序”,它主要用 vbscript 编写,但使用可视化编辑器设计。我不知道足够的 vbscript 完全手工完成。
    • 如果您不介意我问,您为什么要尝试在 vbscript 中编写这样的应用程序?为什么不用VB.NET 编写呢?对于表单应用程序,即使是 vb6 也会更好。在这两种环境中,INI 文件的代码几乎是微不足道的。
    • 我有 vb 2008 express,我可以用它制作 .net 的东西吗?如果是这样,怎么做?感谢您对这个顺便说一句的所有帮助,我真的很感激。
    • 现在你正在赶上。在 vb2008 express 中创建一个 Winforms 应用程序。如果你卡住了,应该有一些 vb2008 express 附带的教程。我会尽快发布 vb.net 的 INI 代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 2022-12-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    相关资源
    最近更新 更多