编辑 INI 文件将 garbage/chinese 个字符写入输出文件
Editing INI file writes garbage/chinese characters to the output file
我想在INI文件中编辑一行代码如下:
iniWrite "new.INI","Settings","Destination","\Backups\test1\"
'
'Delete a key:-
' iniWrite "game.INI","scores","Alan",""
'
'Delete a section:-
' iniWrite "game.INI","scores","",""
Sub INIWrite(strFile,strSection,strKey,strValue)
Dim FSO 'File system object
Dim objReadFile 'INI file to read line by line
Dim objWriteFile 'Temp INI file to write line by line
Dim strLine 'String line read
Dim blnChanging 'Checking mode on\off
Dim blnFoundSect 'Found a section flag
Dim blnFoundKey 'Found a key flag
Dim blnSkipWrite 'Write to temp file on/off
Dim intKeySize 'Size of key to search for
Set FSO = CreateObject("Scripting.FileSystemObject")
'---- No section error
If strSection ="" Then Exit Sub
'---- Equal sign in key name error
If Instr(strKey,"=") then Exit Sub
'---- Carriage return and or line feed in value error
If Instr(strValue,VBCR) or Instr(strValue,VBLF) then Exit Sub
'---- User supplied section and Value, but no key error!
If strSection <>"" and strKey="" and strValue<>"" then Exit Sub
'---- Does INI exist?
If Not FSO.FileExists(strFile) Then
'---- You can't delete a section or key from a none existing INI!
If strKey="" or strValue="" Then Exit sub
'---- No INI so make one and add the section\key....then exit.
Set objWriteFile = FSO.CreateTextFile(strFile,2)
objWriteFile.WriteLine "[" & strSection & "]"
objWriteFile.WriteLine strKey & "=" & strValue
objWriteFile.close
Exit Sub
End if
'---- Set up read and write INI files
Set objReadFile = FSO.OpenTextFile(strFile,1)
Set objWriteFile = FSO.CreateTextFile(strFile & "INITMP",2)
blnChanging = True
blnFoundSect = False
blnFoundKey = False
blnSkipWrite = False
intKeySize = Len(strKey)+1
'---- Scan through INI line by line
Do While Not objReadFile.AtEndOfStream
strLine= objReadFile.ReadLine
'---- Checking mode (disabled once a key has changed)
If blnChanging Then
'------ Key check (only if found section)
If blnFoundSect Then
'---- Found key
If Left(strLine,intKeySize) = strKey & "=" then
'---- Delete key
If strValue="" then
strLine="=" '<--- skips next line to write
'---- Or edit key
Else
strLine = strKey & "=" & strValue
End if
blnFoundKey=True
blnChanging = False
End if
'---- Next section
If Left(strLine,1)="[" Then
'---- Didn't find key in previous section, so make it now (if not deleting)
if blnFoundKey=False and strValue<>"" Then
objWriteFile.WriteLine strKey & "=" & strValue
blnFoundKey=True
blnChanging = False
End if
End if
'------ Section check
Else
If Left(strLine,1)="[" Then
'---- If we where deleting the last section, then re-enable writing.
blnSkipWrite=False
'---- Found section
If strLine = "[" & strSection & "]" Then
'---- Delete section
If strKey="" Then
blnSkipWrite=True
'---- Or flag as found
Else
blnFoundSect=True
End if
End if
End if
End if
End If
'---- Write line to temp INI, if possible
If strLine<>"=" and blnSkipWrite=False then objWriteFile.WriteLine strLine
Loop
'---- Didn't find section at all so append section\key.
If blnFoundSect=False and strKey<>"" and strValue<>"" Then
objWriteFile.WriteLine "[" & strSection & "]"
objWriteFile.WriteLine strKey & "=" & strValue
'---- Didn't find key but was the last section, so append key.
Else
if blnFoundKey=False and strValue<>"" Then
objWriteFile.WriteLine strKey & "=" & strValue
End if
End if
'---- Close files
objReadFile.close
objWriteFile.close
'---- Delete main INI and replace with copy.
FSO.DeleteFile strFile,True
FSO.MoveFile strFile & "INITMP",strFile
End Sub
下面是我要为 Section= Settings
、Key=Destination
、Value=\Backup\folderr1
.
编辑的文件 (new.ini
)
[Settings]
GUID_Pushover=
SMTPCharset=
EmailLogNotMan=N
GUID_EmailLog=
SMTPPasswordPrompt=N
LogLinks=N
GUID_WhenPrograms=
FTPIsSFTP=N
GUID_DestFTP=
SFTPHostKeyTooBig=N
DiffOnTop=N
SecurityTypes=0
CompareSecurity=N
PushOverAppToekn=
PushOverDevice=
PushOverMsg=
PushOverTitle=
PushOverUserID=
PushOver=N
IgnoreCreateDateTime=Y
IgnoreDirModDateTime=Y
CreateTimeComp=0
CreateTimeSince=0
CreateDateTime=1899123100000000000
CreateTimeUnit=3
CreateTime=0
DeltaMinSizeMB=500
DeltaExcMasks=
DeltaIncMasks=*
DeltaNoFilters=Y
DeltaExprType=2
DeltaVersionDest=N
RunAfterEnabled=N
RunBeforeEnabled=N
HistoryGridState=
SBFSOnStartUnat=N
SBFSOnStart=N
SBFSPassword=
SBFSUsername=
SBFSPort=0
SBFSHostname=
SBFSIsName=N
SBFSMulti=N
SBFS=N
MTPOnConnectUnat=N
MTPOnConnect=N
MTPSetLocal=N
MTPName=
MTP=
CloudGlacierDays=1
CloudNotUseDelta=N
CloudDBUpload=N
NetDestNoDefault=N
NetSourceNoDefault=N
VerifyExprType=2
VerifyExcMasks=
VerifyIncMasks=*
VerifyNoFilter=Y
CopyResume=N
WarnDelDestPct=0
WarnDelDest=N
WarnDelSrcPct=0
WarnDelSrc=N
NotReplaceWithEmpty=N
BackupSparse=N
BgWatchWaitIdle=N
BgIdleUnit=0
BgIdleInterval=1
BgIdleRun=N
UseLargeCache=N
SFTPHostKey=
EmailSMTPProtocol=0
SMTPProtocol=0
FTPPortMode=0
CloudProxyPassword=
CloudProxyUsername=
CloudProxyPORT=1
CloudProxyHostname=
CloudProxy=N
FTPForceList=Y
FTPAltParser=N
FTPCustomListCmd=LIST -la
FTPUseCustomList=N
BackupEmailExportFolder=
BackupEmailExport=
BackupEmailFilename=%EMAIL_SUBJECT% [%EMAIL_IDORMD5%].eml
BackupEmailIMAP4Folder=
BackupEmailPasswordPrompt=N
BackupEmailPassword=
BackupEmailUsername=
BackupEmailSSL=N
BackupEmailPort=0
BackupEmailIMAP4=0
BackupEmailHostname=
BackupEmailAuth=N
DestIsBackupEmail=N
CloudKBPS=0
CloudS3Emulate=N
CloudUseSSE=N
CloudUseRRS=Y
CloudItemsPerCall=-1
CloudThreads=5
CloudTimeout=60
CloudAccessPolicy=0
CloudCompleteScan=Y
CloudUseSSL=N
CloudBucket=
CloudPasswordPrompt=N
CloudPassword=
CloudUsername=
CloudURL=
CloudType=0
DestIsCloud=N
TreeColour=536870911
RunProgStopInt=N
RunProgStop=
RunProgStartInt=N
RunProgStart=
BgWatchWait=0
PromptFailure=0
SSIgnoreChanges=N
OnInsertHWSerial=
StopWinSleep=N
LogNoSuccess=N
WarnDelAllPct=100
IgnoreEncrypted=N
DestBurnNoSplit=N
EmailLogZipPassword=
EmailLogZipEncLevel=0
EmailLogNotSim=N
CopySymLink=N
SSBFCCChoice=4
SSDFCCChoice=4
SSSFCCChoice=4
CaseFileChoice=4
SSBDCCChoice=4
SSDDCCChoice=4
SSSDCCChoice=4
CaseDirChoice=4
OnlyVSSDest=N
OnlyVSSSrc=N
DestBurnNoProfile=N
EmailDelIgnore=N
LogHistory=0
IgnoreOffline=N
EmailSMTPTransferEnc=-1
EmailSMTPHeaderEnc=-1
SMTPTransferEnc=1
SMTPHeaderEnc=2
TimeLimitUnit=2
TimeLimitValue=23
TimeLimit=N
UseHashingAlways=N
FTPFilenameTrans=Y
GUID=C2200E8851B5420EA683311C235E1D74
ProfileCD=35 12 98 52 137 25 204 19 98 141 38 198 152 26 6 129 152 77 153
DestBurnCache=N
DestBurnLongJ=Y
DestBurnDelim=N
DestBurnISOLevel=1
DestBurnBootSec=1
DestBurnBootSeg=7C0
DestBurnBootEmu=2
DestBurnBootImg=
DestBurnBoot=N
DestNameChanged=1
DestBurnFormat=0
DestIsISO=0
DestIsBurn=N
PriorityAuto=3
RunBeforeTimeoutAbort=N
CompPasswordPrompt=N
FTPPasswordPrompt=N
FTPUseHost=N
FTPCalcDTOffset=N
LogWarnFileGone=N
EmailMaskAttach=N
SFTPKeyPassword=
SFTPKeyFilename=
FldrTreeDisable=N
FSNoFilters=N
RunBeforeNoLog=N
RunAfterChanges=N
DestIsScript=
SilentDestFail=N
SilentSourceFail=N
Scripts=
LogNoSkipped=N
SSRDDetect=N
SSRSDetect=N
DiffShowSkippedRename=N
FldrTreeShowBoth=Y
EmailCompName=
SMTPCompName=
FTPKeepAlive=N
ShowNotes=N
RunAfterLog=N
CopyDesktopINI=N
VerExcMasks=
VerIncMasks=*
VerNoFilters=Y
VerExprType=2
FullDestination=
FastBackupUseFull=N
LogSMART=N
LogDriveSerials=N
SayPrompt=
SayEndFails=
SayEnd=
SayStart=
EmailSBMailbox=N
EmailSMTPBody=N
FullBackup=Y
EmailGetSSL=-1
EmailGetIMAP4Folder=INBOX
EmailGetPasswordPrompt=N
EmailGetPassword=
EmailGetUsername=
EmailGetAuth=N
EmailGetIMAP4=0
EmailGetPort=0
EmailGetHostname=
EmailSMTPSSL=-1
EmailSMTPUsername=
EmailSMTPAuth=N
EmailSMTPFrom=
EmailSMTPTo=
EmailSMTPPasswordPrompt=N
EmailSMTPPassword=
EmailSMTPSubject=
EmailSMTPBCC=
EmailSMTPCC=
EmailSMTPReceipt=
EmailSMTPReplyTo=
EmailSMTPPort=0
EmailSMTPHostname=
DestIsEmail=N
FastBackupType=0
AttribMask=0
AutoClose=
AutoCollapse=Y
BackupFallback=N
BandwidthKBPS=0
BgInteractive=N
BgInterval=12
BgRun=Y
BgUnit=2
BgWarnOnExit=N
BgWatchAttended=N
BgWatchDest=N
BgWatchSrc=N
ClearArchive=N
ClearReadOnly=N
CompEncLevel=0
CompLevel=5
CompNTFSDest=N
CompNTFSSrc=N
CompPassword=
Compression=0
CopyCreateDate=N
CopyDirAttrs=N
CopyDirSec=N
CopyMethod=0
CreateBaseFolders=Y
DataPortMax=0
DataPortMin=0
DelDest=N
DelEmptyDestDirs=N
DelEmptyDestDirsNotFail=N
DelEmptySrcDirs=N
DelEmptySrcDirsNotFail=N
DelFilesForEmpty=
DelSrc=N
Destination=\Backups\test1\
DestIsFTP=Y
DestLabel=Destination
DestOnlyChoice=3
DestOnlyDelDays=0
DestOnlyDirChoice=7
DestPassword=
DestShortcutRoot=
DestUsername=
DisplayLog=N
DisplayLogError=N
DrivePrompt=N
DST=Y
DynFastBackup=N
EjectDest=N
EjectSource=N
EmailLog=N
EmailLogAttachErrOnly=N
EmailLogCompress=N
EmailLogDiffOnly=N
EmailLogErrOnly=N
EmailLogNoAttach=N
EmailZipFilename=
Expert=Y
ExternalIP=
FastBackup=N
FastBackupDelDest=N
FastBackupEquals=0
FastBackupValue=
FastBackupWhen=Never, manually only
FastDifferential=N
FileExt=
FldrTreeShowDest=Y
FldrTreeShowSrc=Y
Flush=N
ForceBinary=N
ForceClose=N
ForceDateTime=Y
FSExcMasks=
FSExprType=2
FSIncMasks=*\:*\*
FTPAllocate=N
FTPBPS=0
FTPClientCert=[Default]
FTPEncMethod=N
FTPHostname=
FTPMDTMSyntax=0
FTPModeZ=N
FTPMustBeEncrypted=N
FTPNotGMT=N
FTPPassive=N
FTPPassword=36 13 198 75 171 56 76
FTPPort=21
FTPProxy=N
FTPQuote=
FTPReadTimeout=60
FTPRetries=5
FTPRetriesSecs=3
FTPSetLocal=Y
FTPTZ=
FTPUsername=backup
FTPUT8=0
HotKeyUnattended=N
IgnoreHidden=N
IgnoreJP=Y
IgnoreNotArch=N
IgnoreReadOnly=N
IgnoreSize=N
IgnoreSystem=N
IgnoreTime=N
ImplicitSSL=N
KeepNewer=N
LoadDest=N
LoadSource=N
LockPrompt=N
LogIgnoreDest=N
LogIgnoreSrc=N
MaxSize=0
MinSize=0
ModTime=0
ModTimeComp=0
ModTimeSince=0
ModTimeUnit=3
NetDestFirst=N
NetDestNoDiscon=Y
NetSourceFirst=N
NetSourceNoDiscon=Y
NeverDelDirs=Y
NotDelReadOnly=N
NotRepReadOnly=N
NoVSS=N
OnInsert=N
OnInsertDrive=0
OnInsertLabel=
OnInsertSerial=
OnInsertUnattended=N
OnShutdown=N
PauseSecs=0
Priority=3
ProfilePassword=
ProfileType=1
ProxyHostname=
ProxyPassword=
ProxyPort=1
ProxyType=0
ProxyUsername=
ReplaceOnReboot=N
RunAfter=
RunAfterDoPause=N
RunAfterFail=N
RunAfterPause=10
RunAfterSim=N
RunAfterWait=N
RunBefore=
RunBeforeAbort=N
RunBeforeCheckVal=N
RunBeforeDoPause=N
RunBeforePause=10
RunBeforeSim=N
RunBeforeValues=
RunBeforeWait=N
RunHotKey=0
SafeCopy=Y
ShellConfirm=N
ShellDirConfirm=N
ShellShowErr=N
ShellShowProg=Y
ShellUndo=N
ShutdownUnattended=N
SingleFile=N
SkipDiff=N
SmartSync=N
SMTPAuth=N
SMTPBCC=
SMTPBody=N
SMTPCC=
SMTPFrom=
SMTPHostname=
SMTPPassword=
SMTPPort=25
SMTPReceipt=
SMTPReplyTo=
SMTPSSL=0
SMTPSubject=
SMTPTo=
SMTPUsername=
Source=D:\Backup\
SourceOnlyChoice=1
SourceOnlyDirChoice=7
SrcLabel=Source
SrcOnlyDelDays=0
SrcPassword=
SrcShortcutRoot=
SrcUsername=
SSDDChoice=2
SSDDMChoice=4
SSDSChoice=2
SSDSMChoice=4
SSLEncryptDC=N
SSMBChoice=7
SSMBChoiceMove=N
SSMDChoice=2
SSMDChoiceMove=N
SSMSChoice=1
SSMSChoiceMove=N
SSNBChoice=7
SSNBChoiceMove=N
SSNDChoice=1
SSNSChoice=1
SyncChoice=1
SyncChoiceMove=N
TimeDiff=2
UpdShortcuts=N
UseCCC=N
UseHashing=N
Verify=N
Version=21
VersionDest=0
VersionDestMaxAge=14
VersionDestMaxVers=3
VersionSrc=0
VersionSrcMaxAge=14
VersionSrcMaxVers=3
WarnDelAll=Y
ZipFilter=.7z,.ace,.alz,.apk,.arc,.arj,.avi,.b1,.bh,.bwt,.bz2,.cab,.cdx,.cfs,.dar,.dmg,.gho,.gif,.gz,.gzip,.ice,.j,.jar,.jpeg,.jpg,.kgb,.lha,.lzh,.lzma,.mov,.mp1,.mp2,.mp3,.mpeg,.mpg,.pak,.partimg,.pea,.png,.qda,.rar,.sfx,.sitx,.sqx,.swf,.tbz2,.tgz,.tlz,.tib,.tif,.tiff,.wim,.wmv,.wvl,.xar,.z,.zip,.zipx,.zoo,.zpaq,.zz
ZipOpen=N
ZipSFX=N
ZipSpan=N
ZipSplit=0
ZipTemp=
LastRun=14
LastRunDT=2015051112072300440
LastSucRunDt=2015051112072300440
这是 运行 之后的样子(只有输出文件的前几行):
[Settings]
䜀唀䤀䐀开倀甀猀栀漀瘀攀爀㴀ഀഀSMTPCharset=
䔀洀愀椀氀䰀漀最一漀琀䴀愀渀㴀一ഀഀGUID_EmailLog=
匀䴀吀倀倀愀猀猀眀漀爀搀倀爀漀洀瀀琀㴀一ഀഀLogLinks=N
䜀唀䤀䐀开圀栀攀渀倀爀漀最爀愀洀猀㴀ഀഀFTPIsSFTP=N
䜀唀䤀䐀开䐀攀猀琀䘀吀倀㴀ഀഀSFTPHostKeyTooBig=N
䐀椀昀昀伀渀吀漀瀀㴀一ഀഀSecurityTypes=0
䌀漀洀瀀愀爀攀匀攀挀甀爀椀琀礀㴀一ഀഀPushOverAppToekn=
倀甀猀栀伀瘀攀爀䐀攀瘀椀挀攀㴀ഀഀPushOverMsg=
倀甀猀栀伀瘀攀爀吀椀琀氀攀㴀ഀഀPushOverUserID=
倀甀猀栀伀瘀攀爀㴀一ഀഀIgnoreCreateDateTime=Y
䤀最渀漀爀攀䐀椀爀䴀漀搀䐀愀琀攀吀椀洀攀㴀夀ഀഀCreateTimeComp=0
䌀爀攀愀琀攀吀椀洀攀匀椀渀挀攀㴀 ഀഀCreateDateTime=1899123100000000000
䌀爀攀愀琀攀吀椀洀攀唀渀椀琀㴀㌀ഀഀCreateTime=0
䐀攀氀琀愀䴀椀渀匀椀稀攀䴀䈀㴀㔀 ഀഀDeltaExcMasks=
mojibake 的警示故事。下一个脚本重现了您的问题并显示了纠正它的正确方法(可能是多种方法之一)。
从创建纯文本文件开始,将其保存为 ASCII 编码(或 Ansi 编码,对于学究),即一个字符==一个字节,命名为_ASCII.txt
。然后,脚本创建更多文件如下(描述文件 names 被截断以提高可读性):
to_utf16
子例程复制 _ASCII.txt
并将其保存在 UTF16-LE 编码中 BOM;输出文件名 _UTF16.txt
;
Wrong
子例程使用 OpenTextFile
和 CreateTextFile
文件系统方法的 默认编码 复制该 _UTF16.txt
文件(两种方法都假定一个 ASCII 文件);输出文件名 _Wrong.txt
。此子例程通过对输入和输出文件(从您的脚本复制和粘贴的代码)使用 不正确的编码 来重现您的问题;
Good
子例程使用上述文件系统方法的 正确编码 复制 _UTF16.txt
文件(Unicode强制);输出文件名 _Good.txt
.
脚本:
option explicit
Dim FSO, objReadFile, objWriteFile, strLine, strFldr
Set FSO = CreateObject("Scripting.FileSystemObject")
strFldr = "D:\VB_scripts\SO\files_In\"
to_utf16 strFldr & "30329877_ASCII.txt", strFldr & "30329877_UTF16.txt"
Wrong strFldr & "30329877_UTF16.txt", strFldr & "30329877_Wrong.txt"
Good strFldr & "30329877_UTF16.txt", strFldr & "30329877_Good.txt"
Sub Wrong( strFile, strElif)
Set objReadFile = FSO.OpenTextFile(strFile,1)
Set objWriteFile = FSO.CreateTextFile(strElif,2)
aux_copy
End Sub
Sub Good( strFile, strElif)
Set objReadFile = FSO.OpenTextFile(strFile,ForReading,False,OpenAsUnicode)
Set objWriteFile = FSO.CreateTextFile(strElif,True,True)
aux_copy
End Sub
Sub to_utf16( strFile, strElif)
Set objReadFile = FSO.OpenTextFile(strFile,ForReading,False,OpenAs__ASCII)
Set objWriteFile = FSO.CreateTextFile(strElif,True,True)
aux_copy
End Sub
Const ForReading=1, ForWriting=2, ForAppending=8
Const OpenAsDefault = -2 ' Opens the file using the system default
Const OpenAsUnicode = -1 ' Opens the file as Unicode
Const OpenAs__ASCII = 0 ' Opens the file as ASCII
Sub aux_copy
Do While Not objReadFile.AtEndOfStream
strLine= objReadFile.ReadLine
objWriteFile.WriteLine strLine
Loop
objReadFile.close
objWriteFile.close
End Sub
Wscript.Echo Wscript.Scriptname & " done"
输出:
==>cscript D:\VB_scripts\SO329877.vbs
30329877.vbs done
==>type D:\VB_scripts\SO\files_In329877_Good.txt
[Settings]
GUID_Pushover=
SMTPCharset=
EmailLogNotMan=N
==>type D:\VB_scripts\SO\files_In329877_Wrong.txt
䜀唀䤀䐀开倀甀猀栀漀瘀攀爀㴀ഀഀ
䔀洀愀椀氀䰀漀最一漀琀䴀愀渀㴀一ഀഀ
==>
事实上,我的文本编辑器读取 30329877_Wrong.txt
文件如下:
[Settings]
䜀唀䤀䐀开倀甀猀栀漀瘀攀爀㴀ഀഀ
SMTPCharset=
䔀洀愀椀氀䰀漀最一漀琀䴀愀渀㴀一ഀഀ
最后,为了说明:dir D:\VB_scripts\SO\files_In329877*
(截断的)输出。
22.05.2015 11:21 60 30329877_ASCII.txt
22.05.2015 14:07 122 30329877_UTF16.txt
22.05.2015 14:07 122 30329877_Good.txt
22.05.2015 14:07 128 30329877_Wrong.txt
4 File(s) 432 bytes
==>
我想在INI文件中编辑一行代码如下:
iniWrite "new.INI","Settings","Destination","\Backups\test1\"
'
'Delete a key:-
' iniWrite "game.INI","scores","Alan",""
'
'Delete a section:-
' iniWrite "game.INI","scores","",""
Sub INIWrite(strFile,strSection,strKey,strValue)
Dim FSO 'File system object
Dim objReadFile 'INI file to read line by line
Dim objWriteFile 'Temp INI file to write line by line
Dim strLine 'String line read
Dim blnChanging 'Checking mode on\off
Dim blnFoundSect 'Found a section flag
Dim blnFoundKey 'Found a key flag
Dim blnSkipWrite 'Write to temp file on/off
Dim intKeySize 'Size of key to search for
Set FSO = CreateObject("Scripting.FileSystemObject")
'---- No section error
If strSection ="" Then Exit Sub
'---- Equal sign in key name error
If Instr(strKey,"=") then Exit Sub
'---- Carriage return and or line feed in value error
If Instr(strValue,VBCR) or Instr(strValue,VBLF) then Exit Sub
'---- User supplied section and Value, but no key error!
If strSection <>"" and strKey="" and strValue<>"" then Exit Sub
'---- Does INI exist?
If Not FSO.FileExists(strFile) Then
'---- You can't delete a section or key from a none existing INI!
If strKey="" or strValue="" Then Exit sub
'---- No INI so make one and add the section\key....then exit.
Set objWriteFile = FSO.CreateTextFile(strFile,2)
objWriteFile.WriteLine "[" & strSection & "]"
objWriteFile.WriteLine strKey & "=" & strValue
objWriteFile.close
Exit Sub
End if
'---- Set up read and write INI files
Set objReadFile = FSO.OpenTextFile(strFile,1)
Set objWriteFile = FSO.CreateTextFile(strFile & "INITMP",2)
blnChanging = True
blnFoundSect = False
blnFoundKey = False
blnSkipWrite = False
intKeySize = Len(strKey)+1
'---- Scan through INI line by line
Do While Not objReadFile.AtEndOfStream
strLine= objReadFile.ReadLine
'---- Checking mode (disabled once a key has changed)
If blnChanging Then
'------ Key check (only if found section)
If blnFoundSect Then
'---- Found key
If Left(strLine,intKeySize) = strKey & "=" then
'---- Delete key
If strValue="" then
strLine="=" '<--- skips next line to write
'---- Or edit key
Else
strLine = strKey & "=" & strValue
End if
blnFoundKey=True
blnChanging = False
End if
'---- Next section
If Left(strLine,1)="[" Then
'---- Didn't find key in previous section, so make it now (if not deleting)
if blnFoundKey=False and strValue<>"" Then
objWriteFile.WriteLine strKey & "=" & strValue
blnFoundKey=True
blnChanging = False
End if
End if
'------ Section check
Else
If Left(strLine,1)="[" Then
'---- If we where deleting the last section, then re-enable writing.
blnSkipWrite=False
'---- Found section
If strLine = "[" & strSection & "]" Then
'---- Delete section
If strKey="" Then
blnSkipWrite=True
'---- Or flag as found
Else
blnFoundSect=True
End if
End if
End if
End if
End If
'---- Write line to temp INI, if possible
If strLine<>"=" and blnSkipWrite=False then objWriteFile.WriteLine strLine
Loop
'---- Didn't find section at all so append section\key.
If blnFoundSect=False and strKey<>"" and strValue<>"" Then
objWriteFile.WriteLine "[" & strSection & "]"
objWriteFile.WriteLine strKey & "=" & strValue
'---- Didn't find key but was the last section, so append key.
Else
if blnFoundKey=False and strValue<>"" Then
objWriteFile.WriteLine strKey & "=" & strValue
End if
End if
'---- Close files
objReadFile.close
objWriteFile.close
'---- Delete main INI and replace with copy.
FSO.DeleteFile strFile,True
FSO.MoveFile strFile & "INITMP",strFile
End Sub
下面是我要为 Section= Settings
、Key=Destination
、Value=\Backup\folderr1
.
new.ini
)
[Settings]
GUID_Pushover=
SMTPCharset=
EmailLogNotMan=N
GUID_EmailLog=
SMTPPasswordPrompt=N
LogLinks=N
GUID_WhenPrograms=
FTPIsSFTP=N
GUID_DestFTP=
SFTPHostKeyTooBig=N
DiffOnTop=N
SecurityTypes=0
CompareSecurity=N
PushOverAppToekn=
PushOverDevice=
PushOverMsg=
PushOverTitle=
PushOverUserID=
PushOver=N
IgnoreCreateDateTime=Y
IgnoreDirModDateTime=Y
CreateTimeComp=0
CreateTimeSince=0
CreateDateTime=1899123100000000000
CreateTimeUnit=3
CreateTime=0
DeltaMinSizeMB=500
DeltaExcMasks=
DeltaIncMasks=*
DeltaNoFilters=Y
DeltaExprType=2
DeltaVersionDest=N
RunAfterEnabled=N
RunBeforeEnabled=N
HistoryGridState=
SBFSOnStartUnat=N
SBFSOnStart=N
SBFSPassword=
SBFSUsername=
SBFSPort=0
SBFSHostname=
SBFSIsName=N
SBFSMulti=N
SBFS=N
MTPOnConnectUnat=N
MTPOnConnect=N
MTPSetLocal=N
MTPName=
MTP=
CloudGlacierDays=1
CloudNotUseDelta=N
CloudDBUpload=N
NetDestNoDefault=N
NetSourceNoDefault=N
VerifyExprType=2
VerifyExcMasks=
VerifyIncMasks=*
VerifyNoFilter=Y
CopyResume=N
WarnDelDestPct=0
WarnDelDest=N
WarnDelSrcPct=0
WarnDelSrc=N
NotReplaceWithEmpty=N
BackupSparse=N
BgWatchWaitIdle=N
BgIdleUnit=0
BgIdleInterval=1
BgIdleRun=N
UseLargeCache=N
SFTPHostKey=
EmailSMTPProtocol=0
SMTPProtocol=0
FTPPortMode=0
CloudProxyPassword=
CloudProxyUsername=
CloudProxyPORT=1
CloudProxyHostname=
CloudProxy=N
FTPForceList=Y
FTPAltParser=N
FTPCustomListCmd=LIST -la
FTPUseCustomList=N
BackupEmailExportFolder=
BackupEmailExport=
BackupEmailFilename=%EMAIL_SUBJECT% [%EMAIL_IDORMD5%].eml
BackupEmailIMAP4Folder=
BackupEmailPasswordPrompt=N
BackupEmailPassword=
BackupEmailUsername=
BackupEmailSSL=N
BackupEmailPort=0
BackupEmailIMAP4=0
BackupEmailHostname=
BackupEmailAuth=N
DestIsBackupEmail=N
CloudKBPS=0
CloudS3Emulate=N
CloudUseSSE=N
CloudUseRRS=Y
CloudItemsPerCall=-1
CloudThreads=5
CloudTimeout=60
CloudAccessPolicy=0
CloudCompleteScan=Y
CloudUseSSL=N
CloudBucket=
CloudPasswordPrompt=N
CloudPassword=
CloudUsername=
CloudURL=
CloudType=0
DestIsCloud=N
TreeColour=536870911
RunProgStopInt=N
RunProgStop=
RunProgStartInt=N
RunProgStart=
BgWatchWait=0
PromptFailure=0
SSIgnoreChanges=N
OnInsertHWSerial=
StopWinSleep=N
LogNoSuccess=N
WarnDelAllPct=100
IgnoreEncrypted=N
DestBurnNoSplit=N
EmailLogZipPassword=
EmailLogZipEncLevel=0
EmailLogNotSim=N
CopySymLink=N
SSBFCCChoice=4
SSDFCCChoice=4
SSSFCCChoice=4
CaseFileChoice=4
SSBDCCChoice=4
SSDDCCChoice=4
SSSDCCChoice=4
CaseDirChoice=4
OnlyVSSDest=N
OnlyVSSSrc=N
DestBurnNoProfile=N
EmailDelIgnore=N
LogHistory=0
IgnoreOffline=N
EmailSMTPTransferEnc=-1
EmailSMTPHeaderEnc=-1
SMTPTransferEnc=1
SMTPHeaderEnc=2
TimeLimitUnit=2
TimeLimitValue=23
TimeLimit=N
UseHashingAlways=N
FTPFilenameTrans=Y
GUID=C2200E8851B5420EA683311C235E1D74
ProfileCD=35 12 98 52 137 25 204 19 98 141 38 198 152 26 6 129 152 77 153
DestBurnCache=N
DestBurnLongJ=Y
DestBurnDelim=N
DestBurnISOLevel=1
DestBurnBootSec=1
DestBurnBootSeg=7C0
DestBurnBootEmu=2
DestBurnBootImg=
DestBurnBoot=N
DestNameChanged=1
DestBurnFormat=0
DestIsISO=0
DestIsBurn=N
PriorityAuto=3
RunBeforeTimeoutAbort=N
CompPasswordPrompt=N
FTPPasswordPrompt=N
FTPUseHost=N
FTPCalcDTOffset=N
LogWarnFileGone=N
EmailMaskAttach=N
SFTPKeyPassword=
SFTPKeyFilename=
FldrTreeDisable=N
FSNoFilters=N
RunBeforeNoLog=N
RunAfterChanges=N
DestIsScript=
SilentDestFail=N
SilentSourceFail=N
Scripts=
LogNoSkipped=N
SSRDDetect=N
SSRSDetect=N
DiffShowSkippedRename=N
FldrTreeShowBoth=Y
EmailCompName=
SMTPCompName=
FTPKeepAlive=N
ShowNotes=N
RunAfterLog=N
CopyDesktopINI=N
VerExcMasks=
VerIncMasks=*
VerNoFilters=Y
VerExprType=2
FullDestination=
FastBackupUseFull=N
LogSMART=N
LogDriveSerials=N
SayPrompt=
SayEndFails=
SayEnd=
SayStart=
EmailSBMailbox=N
EmailSMTPBody=N
FullBackup=Y
EmailGetSSL=-1
EmailGetIMAP4Folder=INBOX
EmailGetPasswordPrompt=N
EmailGetPassword=
EmailGetUsername=
EmailGetAuth=N
EmailGetIMAP4=0
EmailGetPort=0
EmailGetHostname=
EmailSMTPSSL=-1
EmailSMTPUsername=
EmailSMTPAuth=N
EmailSMTPFrom=
EmailSMTPTo=
EmailSMTPPasswordPrompt=N
EmailSMTPPassword=
EmailSMTPSubject=
EmailSMTPBCC=
EmailSMTPCC=
EmailSMTPReceipt=
EmailSMTPReplyTo=
EmailSMTPPort=0
EmailSMTPHostname=
DestIsEmail=N
FastBackupType=0
AttribMask=0
AutoClose=
AutoCollapse=Y
BackupFallback=N
BandwidthKBPS=0
BgInteractive=N
BgInterval=12
BgRun=Y
BgUnit=2
BgWarnOnExit=N
BgWatchAttended=N
BgWatchDest=N
BgWatchSrc=N
ClearArchive=N
ClearReadOnly=N
CompEncLevel=0
CompLevel=5
CompNTFSDest=N
CompNTFSSrc=N
CompPassword=
Compression=0
CopyCreateDate=N
CopyDirAttrs=N
CopyDirSec=N
CopyMethod=0
CreateBaseFolders=Y
DataPortMax=0
DataPortMin=0
DelDest=N
DelEmptyDestDirs=N
DelEmptyDestDirsNotFail=N
DelEmptySrcDirs=N
DelEmptySrcDirsNotFail=N
DelFilesForEmpty=
DelSrc=N
Destination=\Backups\test1\
DestIsFTP=Y
DestLabel=Destination
DestOnlyChoice=3
DestOnlyDelDays=0
DestOnlyDirChoice=7
DestPassword=
DestShortcutRoot=
DestUsername=
DisplayLog=N
DisplayLogError=N
DrivePrompt=N
DST=Y
DynFastBackup=N
EjectDest=N
EjectSource=N
EmailLog=N
EmailLogAttachErrOnly=N
EmailLogCompress=N
EmailLogDiffOnly=N
EmailLogErrOnly=N
EmailLogNoAttach=N
EmailZipFilename=
Expert=Y
ExternalIP=
FastBackup=N
FastBackupDelDest=N
FastBackupEquals=0
FastBackupValue=
FastBackupWhen=Never, manually only
FastDifferential=N
FileExt=
FldrTreeShowDest=Y
FldrTreeShowSrc=Y
Flush=N
ForceBinary=N
ForceClose=N
ForceDateTime=Y
FSExcMasks=
FSExprType=2
FSIncMasks=*\:*\*
FTPAllocate=N
FTPBPS=0
FTPClientCert=[Default]
FTPEncMethod=N
FTPHostname=
FTPMDTMSyntax=0
FTPModeZ=N
FTPMustBeEncrypted=N
FTPNotGMT=N
FTPPassive=N
FTPPassword=36 13 198 75 171 56 76
FTPPort=21
FTPProxy=N
FTPQuote=
FTPReadTimeout=60
FTPRetries=5
FTPRetriesSecs=3
FTPSetLocal=Y
FTPTZ=
FTPUsername=backup
FTPUT8=0
HotKeyUnattended=N
IgnoreHidden=N
IgnoreJP=Y
IgnoreNotArch=N
IgnoreReadOnly=N
IgnoreSize=N
IgnoreSystem=N
IgnoreTime=N
ImplicitSSL=N
KeepNewer=N
LoadDest=N
LoadSource=N
LockPrompt=N
LogIgnoreDest=N
LogIgnoreSrc=N
MaxSize=0
MinSize=0
ModTime=0
ModTimeComp=0
ModTimeSince=0
ModTimeUnit=3
NetDestFirst=N
NetDestNoDiscon=Y
NetSourceFirst=N
NetSourceNoDiscon=Y
NeverDelDirs=Y
NotDelReadOnly=N
NotRepReadOnly=N
NoVSS=N
OnInsert=N
OnInsertDrive=0
OnInsertLabel=
OnInsertSerial=
OnInsertUnattended=N
OnShutdown=N
PauseSecs=0
Priority=3
ProfilePassword=
ProfileType=1
ProxyHostname=
ProxyPassword=
ProxyPort=1
ProxyType=0
ProxyUsername=
ReplaceOnReboot=N
RunAfter=
RunAfterDoPause=N
RunAfterFail=N
RunAfterPause=10
RunAfterSim=N
RunAfterWait=N
RunBefore=
RunBeforeAbort=N
RunBeforeCheckVal=N
RunBeforeDoPause=N
RunBeforePause=10
RunBeforeSim=N
RunBeforeValues=
RunBeforeWait=N
RunHotKey=0
SafeCopy=Y
ShellConfirm=N
ShellDirConfirm=N
ShellShowErr=N
ShellShowProg=Y
ShellUndo=N
ShutdownUnattended=N
SingleFile=N
SkipDiff=N
SmartSync=N
SMTPAuth=N
SMTPBCC=
SMTPBody=N
SMTPCC=
SMTPFrom=
SMTPHostname=
SMTPPassword=
SMTPPort=25
SMTPReceipt=
SMTPReplyTo=
SMTPSSL=0
SMTPSubject=
SMTPTo=
SMTPUsername=
Source=D:\Backup\
SourceOnlyChoice=1
SourceOnlyDirChoice=7
SrcLabel=Source
SrcOnlyDelDays=0
SrcPassword=
SrcShortcutRoot=
SrcUsername=
SSDDChoice=2
SSDDMChoice=4
SSDSChoice=2
SSDSMChoice=4
SSLEncryptDC=N
SSMBChoice=7
SSMBChoiceMove=N
SSMDChoice=2
SSMDChoiceMove=N
SSMSChoice=1
SSMSChoiceMove=N
SSNBChoice=7
SSNBChoiceMove=N
SSNDChoice=1
SSNSChoice=1
SyncChoice=1
SyncChoiceMove=N
TimeDiff=2
UpdShortcuts=N
UseCCC=N
UseHashing=N
Verify=N
Version=21
VersionDest=0
VersionDestMaxAge=14
VersionDestMaxVers=3
VersionSrc=0
VersionSrcMaxAge=14
VersionSrcMaxVers=3
WarnDelAll=Y
ZipFilter=.7z,.ace,.alz,.apk,.arc,.arj,.avi,.b1,.bh,.bwt,.bz2,.cab,.cdx,.cfs,.dar,.dmg,.gho,.gif,.gz,.gzip,.ice,.j,.jar,.jpeg,.jpg,.kgb,.lha,.lzh,.lzma,.mov,.mp1,.mp2,.mp3,.mpeg,.mpg,.pak,.partimg,.pea,.png,.qda,.rar,.sfx,.sitx,.sqx,.swf,.tbz2,.tgz,.tlz,.tib,.tif,.tiff,.wim,.wmv,.wvl,.xar,.z,.zip,.zipx,.zoo,.zpaq,.zz
ZipOpen=N
ZipSFX=N
ZipSpan=N
ZipSplit=0
ZipTemp=
LastRun=14
LastRunDT=2015051112072300440
LastSucRunDt=2015051112072300440
这是 运行 之后的样子(只有输出文件的前几行):
[Settings]
䜀唀䤀䐀开倀甀猀栀漀瘀攀爀㴀ഀഀSMTPCharset=
䔀洀愀椀氀䰀漀最一漀琀䴀愀渀㴀一ഀഀGUID_EmailLog=
匀䴀吀倀倀愀猀猀眀漀爀搀倀爀漀洀瀀琀㴀一ഀഀLogLinks=N
䜀唀䤀䐀开圀栀攀渀倀爀漀最爀愀洀猀㴀ഀഀFTPIsSFTP=N
䜀唀䤀䐀开䐀攀猀琀䘀吀倀㴀ഀഀSFTPHostKeyTooBig=N
䐀椀昀昀伀渀吀漀瀀㴀一ഀഀSecurityTypes=0
䌀漀洀瀀愀爀攀匀攀挀甀爀椀琀礀㴀一ഀഀPushOverAppToekn=
倀甀猀栀伀瘀攀爀䐀攀瘀椀挀攀㴀ഀഀPushOverMsg=
倀甀猀栀伀瘀攀爀吀椀琀氀攀㴀ഀഀPushOverUserID=
倀甀猀栀伀瘀攀爀㴀一ഀഀIgnoreCreateDateTime=Y
䤀最渀漀爀攀䐀椀爀䴀漀搀䐀愀琀攀吀椀洀攀㴀夀ഀഀCreateTimeComp=0
䌀爀攀愀琀攀吀椀洀攀匀椀渀挀攀㴀 ഀഀCreateDateTime=1899123100000000000
䌀爀攀愀琀攀吀椀洀攀唀渀椀琀㴀㌀ഀഀCreateTime=0
䐀攀氀琀愀䴀椀渀匀椀稀攀䴀䈀㴀㔀 ഀഀDeltaExcMasks=
mojibake 的警示故事。下一个脚本重现了您的问题并显示了纠正它的正确方法(可能是多种方法之一)。
从创建纯文本文件开始,将其保存为 ASCII 编码(或 Ansi 编码,对于学究),即一个字符==一个字节,命名为_ASCII.txt
。然后,脚本创建更多文件如下(描述文件 names 被截断以提高可读性):
to_utf16
子例程复制_ASCII.txt
并将其保存在 UTF16-LE 编码中 BOM;输出文件名_UTF16.txt
;Wrong
子例程使用OpenTextFile
和CreateTextFile
文件系统方法的 默认编码 复制该_UTF16.txt
文件(两种方法都假定一个 ASCII 文件);输出文件名_Wrong.txt
。此子例程通过对输入和输出文件(从您的脚本复制和粘贴的代码)使用 不正确的编码 来重现您的问题;Good
子例程使用上述文件系统方法的 正确编码 复制_UTF16.txt
文件(Unicode强制);输出文件名_Good.txt
.
脚本:
option explicit
Dim FSO, objReadFile, objWriteFile, strLine, strFldr
Set FSO = CreateObject("Scripting.FileSystemObject")
strFldr = "D:\VB_scripts\SO\files_In\"
to_utf16 strFldr & "30329877_ASCII.txt", strFldr & "30329877_UTF16.txt"
Wrong strFldr & "30329877_UTF16.txt", strFldr & "30329877_Wrong.txt"
Good strFldr & "30329877_UTF16.txt", strFldr & "30329877_Good.txt"
Sub Wrong( strFile, strElif)
Set objReadFile = FSO.OpenTextFile(strFile,1)
Set objWriteFile = FSO.CreateTextFile(strElif,2)
aux_copy
End Sub
Sub Good( strFile, strElif)
Set objReadFile = FSO.OpenTextFile(strFile,ForReading,False,OpenAsUnicode)
Set objWriteFile = FSO.CreateTextFile(strElif,True,True)
aux_copy
End Sub
Sub to_utf16( strFile, strElif)
Set objReadFile = FSO.OpenTextFile(strFile,ForReading,False,OpenAs__ASCII)
Set objWriteFile = FSO.CreateTextFile(strElif,True,True)
aux_copy
End Sub
Const ForReading=1, ForWriting=2, ForAppending=8
Const OpenAsDefault = -2 ' Opens the file using the system default
Const OpenAsUnicode = -1 ' Opens the file as Unicode
Const OpenAs__ASCII = 0 ' Opens the file as ASCII
Sub aux_copy
Do While Not objReadFile.AtEndOfStream
strLine= objReadFile.ReadLine
objWriteFile.WriteLine strLine
Loop
objReadFile.close
objWriteFile.close
End Sub
Wscript.Echo Wscript.Scriptname & " done"
输出:
==>cscript D:\VB_scripts\SO329877.vbs
30329877.vbs done
==>type D:\VB_scripts\SO\files_In329877_Good.txt
[Settings]
GUID_Pushover=
SMTPCharset=
EmailLogNotMan=N
==>type D:\VB_scripts\SO\files_In329877_Wrong.txt
䜀唀䤀䐀开倀甀猀栀漀瘀攀爀㴀ഀഀ
䔀洀愀椀氀䰀漀最一漀琀䴀愀渀㴀一ഀഀ
==>
事实上,我的文本编辑器读取 30329877_Wrong.txt
文件如下:
[Settings]
䜀唀䤀䐀开倀甀猀栀漀瘀攀爀㴀ഀഀ
SMTPCharset=
䔀洀愀椀氀䰀漀最一漀琀䴀愀渀㴀一ഀഀ
最后,为了说明:dir D:\VB_scripts\SO\files_In329877*
(截断的)输出。
22.05.2015 11:21 60 30329877_ASCII.txt
22.05.2015 14:07 122 30329877_UTF16.txt
22.05.2015 14:07 122 30329877_Good.txt
22.05.2015 14:07 128 30329877_Wrong.txt
4 File(s) 432 bytes
==>