VBscript에서 사용자 정의 확장자를 사용하여 외부 파일 쓰기/읽기
-
06-07-2019 - |
문제
VBscript를 사용하여 사용자 정의 확장명(예: .txt 확장자 대신 .cyc를 가질 수 있음)을 사용하여 외부 파일을 쓰거나 읽으려면 어떻게 해야 합니까?
나는 방법을 모르고 그것을 알아낼 수 없는 것 같습니다.파일을 읽을 때 파일의 일부만 읽을 수 있나요?예를 들어, 한 줄이 있다면
string1=안녕하세요!
내 파일 내에서 내 스크립트는 어떻게 string1 줄에서만 읽으며 vbscript 파일의 문자열에 텍스트 값을 할당할 수 있습니까?
그렇다면 파일에 단일 값을 어떻게 쓸 수 있습니까?
명확히 하기 위해 기본적으로 외부 파일을 구성/데이터 파일로 사용하려고 합니다.
이것은 아마도 정말 멍청한 질문일 것입니다. 만약 그렇다면 정말 죄송합니다.
편집하다:이것은 두 부분으로 구성된 질문입니다. 위에 지정된 대로 파일을 읽고 쓰는 코드와 이를 통해 사용자 정의 확장을 사용하는 방법을 알아야 합니다.
해결책
임의의 위치에 있는 텍스트 파일을 읽고 쓰려면 INI 파일을 사용하는 것이 가장 좋습니다.
INI 파일에는 다음과 같은 항목이 포함되어 있습니다.
[owner]
name=John Doe
organization=Acme Products
ini 파일을 읽으려면 다음과 같이 호출할 수 있는 함수가 필요합니다.
Dim s as string
s=ReadINI("c:\myfolder\myfile.ext", "owner", "name")
...s에 "John Doe"를 넣습니다.
이를 수행하는 코드는 다음과 같습니다.http://cwashington.netreach.net/depo/view.asp?Index=553
INI 파일 작성도 같은 방식으로 작동합니다.
또 다른 예는 다음과 같습니다.
WriteINI("c:\myfolder\myfile.ext", "MySection", "MyItem", "MyValue")
다음과 같은 INI 파일을 생성합니다.
[MySection]
MyItem=MyValue
원하는 만큼 다양한 섹션과 항목을 각 섹션 내에 포함할 수 있습니다.원하는 값을 검색하기 위해 해야 할 일은 검색하려는 값의 섹션 이름과 항목 이름으로 ReadINI를 호출하는 것뿐입니다.
다른 팁
다음과 같이 파일 이름 끝의 확장을 포함하기 만하면됩니다.
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/
다음 수업은 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
집진 장치:
- 폴더 c : testArea를 만듭니다.
- 방금 만든 폴더에서 test.vbs라는 텍스트 파일을 만들고 아래 코드를 붙여 넣습니다.
- test.vbs 파일을 두 번 클릭하여 실행하십시오. 동일한 디렉토리에 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")