title: Editing INI file writes garbage/chinese characters to the output file
body: <p>I want to edit a line in the INI file and below is the code:</p>
  
  <pre class="lang-vb prettyprint-override"><code>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 &lt;&gt;"" and strKey="" and strValue&lt;&gt;"" 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 "[" &amp; strSection &amp; "]"
      objWriteFile.WriteLine strKey &amp; "=" &amp; 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 &amp; "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 &amp; "=" then 
  
            '---- Delete key
            If strValue="" then
              strLine="="   '&lt;--- skips next line to write
  
            '---- Or edit key
            Else
              strLine = strKey &amp; "=" &amp; 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&lt;&gt;"" Then
              objWriteFile.WriteLine strKey &amp; "=" &amp; 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 = "[" &amp; strSection &amp; "]" 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&lt;&gt;"=" and blnSkipWrite=False then objWriteFile.WriteLine strLine
    Loop
  
    '---- Didn't find section at all so append section\key.
    If blnFoundSect=False and strKey&lt;&gt;"" and strValue&lt;&gt;"" Then
      objWriteFile.WriteLine "[" &amp; strSection &amp; "]"
      objWriteFile.WriteLine strKey &amp; "=" &amp; strValue
  
    '---- Didn't find key but was the last section, so append key.
    Else
      if blnFoundKey=False and strValue&lt;&gt;"" Then
        objWriteFile.WriteLine strKey &amp; "=" &amp; 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 &amp; "INITMP",strFile 
  End Sub
  </code></pre>
  
  <p>Below is the file I want to edit (<code>new.ini</code>) for <code>Section= Settings</code>, <code>Key=Destination</code>, <code>Value=\Backup\folderr1</code>.</p>
  
  <pre class="lang-none prettyprint-override"><code>[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
  </code></pre>
  
  <p>This is how it looks like after the run (only first few lines from the outputfile):</p>
  
  <pre class="lang-none prettyprint-override"><code>[Settings]
  ਍䜀唀䤀䐀开倀甀猀栀漀瘀攀爀㴀ഀഀSMTPCharset=
  ਍䔀洀愀椀氀䰀漀最一漀琀䴀愀渀㴀一ഀഀGUID_EmailLog=
  ਍匀䴀吀倀倀愀猀猀眀漀爀搀倀爀漀洀瀀琀㴀一ഀഀLogLinks=N
  ਍䜀唀䤀䐀开圀栀攀渀倀爀漀最爀愀洀猀㴀ഀഀFTPIsSFTP=N
  ਍䜀唀䤀䐀开䐀攀猀琀䘀吀倀㴀ഀഀSFTPHostKeyTooBig=N
  ਍䐀椀昀昀伀渀吀漀瀀㴀一ഀഀSecurityTypes=0
  ਍䌀漀洀瀀愀爀攀匀攀挀甀爀椀琀礀㴀一ഀഀPushOverAppToekn=
  ਍倀甀猀栀伀瘀攀爀䐀攀瘀椀挀攀㴀ഀഀPushOverMsg=
  ਍倀甀猀栀伀瘀攀爀吀椀琀氀攀㴀ഀഀPushOverUserID=
  ਍倀甀猀栀伀瘀攀爀㴀一ഀഀIgnoreCreateDateTime=Y
  ਍䤀最渀漀爀攀䐀椀爀䴀漀搀䐀愀琀攀吀椀洀攀㴀夀ഀഀCreateTimeComp=0
  ਍䌀爀攀愀琀攀吀椀洀攀匀椀渀挀攀㴀　ഀഀCreateDateTime=1899123100000000000
  ਍䌀爀攀愀琀攀吀椀洀攀唀渀椀琀㴀㌀ഀഀCreateTime=0
  ਍䐀攀氀琀愀䴀椀渀匀椀稀攀䴀䈀㴀㔀　　ഀഀDeltaExcMasks=
  </code></pre>