Base64 Encode .JPG from request in classic ASP/VBScript - file-upload

I've been stuck on this one for a few days with no progress. Using classic ASP, I need to take an uploaded .JPG file (from html form input type='file') and base64 encode it so that I can send it to a Java web service. The Java web service is simply storing the image (in a SQL image field) in a database. I figured converting to BASE64 was the best way to transfer the parameter in the xml. Here's what I have so far:
HTML:
<label>Upload Picture</label>
<input name="file" id="file" type="file" size=40 /> <br />
ASP:
Dim load
Set load = new Loader
load.initialize
Dim fileData
fileData = load.getFileData("file")
Dim fileName
fileName = LCase(load.getFileName("file"))
Dim fileSize
fileSize = load.getFileSize("file")
Dim objXML
Dim objNode
Dim strB64
Set objXML = Server.CreateObject("MSXML2.DomDocument.3.0")
Set objNode = objXML.createElement("base64")
objNode.dataType = "bin.base64" 'stores binary as base64 string
objNode.nodeTypedValue = fileData 'binary value
strB64 = objNode.Text
LOADER:
the loader is a lot of code (I can copy all of it here if needed). It essentially gets all the bytes from the request and parses them into a dictionary object. Here's how it gets the data:
Class Loader
Private dict
Private Sub Class_Initialize
Set dict = Server.CreateObject("Scripting.Dictionary")
End Sub
Public Sub Initialize
If Request.TotalBytes > 0 Then
Dim binData
binData = Request.BinaryRead(Request.TotalBytes)
getData binData
End If
End Sub
Public Function getFileData(name) '"file"
If dict.Exists(name) Then
getFileData = dict(name).Item("Value")
Else
getFileData = ""
End If
End Function
I can post the sub that parses and stores the binary in a dictionary if needed.
The above code gives this error:
msxml3.dll error '80004005'
Error parsing '????' as bin.base64 datatype.
on this line:
objNode.nodeTypedValue = fileData 'binary value
UPDATE:
Here's where the data is loaded to the dictionary:
Private Sub getData(rawData)
Dim separator
separator = MidB(rawData, 1, InstrB(1, rawData, ChrB(13)) - 1)
Dim lenSeparator
lenSeparator = LenB(separator)
Dim currentPos
currentPos = 1
Dim inStrByte
inStrByte = 1
Dim value, mValue
Dim tempValue
tempValue = ""
While inStrByte > 0
inStrByte = InStrB(currentPos, rawData, separator)
mValue = inStrByte - currentPos
If mValue > 1 Then
value = MidB(rawData, currentPos, mValue)
Dim begPos, endPos, midValue, nValue
Dim intDict
Set intDict = Server.CreateObject("Scripting.Dictionary")
begPos = 1 + InStrB(1, value, ChrB(34))
endPos = InStrB(begPos + 1, value, ChrB(34))
nValue = endPos
Dim nameN
nameN = MidB(value, begPos, endPos - begPos)
Dim nameValue, isValid
isValid = True
If InStrB(1, value, stringToByte("Content-Type")) > 1 Then
begPos = 1 + InStrB(endPos + 1, value, ChrB(34))
endPos = InStrB(begPos + 1, value, ChrB(34))
If endPos = 0 Then
endPos = begPos + 1
isValid = False
End If
midValue = MidB(value, begPos, endPos - begPos)
intDict.Add "FileName", trim(byteToString(midValue))
begPos = 14 + InStrB(endPos + 1, value, stringToByte("Content-Type:"))
endPos = InStrB(begPos, value, ChrB(13))
midValue = MidB(value, begPos, endPos - begPos)
intDict.Add "ContentType", trim(byteToString(midValue))
begPos = endPos + 4
endPos = LenB(value)
nameValue = MidB(value, begPos, ((endPos - begPos) - 1))
Else
nameValue = trim(byteToString(MidB(value, nValue + 5)))
End If
If isValid = True Then
intDict.Add "Value", nameValue
intDict.Add "Name", nameN
dict.Add byteToString(nameN), intDict
End If
End If
currentPos = lenSeparator + inStrByte
Wend
End Sub
Private Function stringToByte(toConv)
Dim tempChar, i
For i = 1 to Len(toConv)
tempChar = Mid(toConv, i, 1)
stringToByte = stringToByte & chrB(AscB(tempChar))
Next
End Function
Private Function byteToString(toConv)
dim i
For i = 1 to LenB(toConv)
byteToString = byteToString & chr(AscB(MidB(toConv,i,1)))
Next
End Function

I finally found something that works! Here's the link:
http://www.motobit.com/tips/detpg_binarytostring/
The issue I was having was that the data from the BinaryRead was multibyte data (which ASP doesn't play well with). MultiByte data must be converted To VT_UI1 | VT_ARRAY in order for the base64 encoding via the Dom Document Object (or nearly any other function - including loading to a stream). This can be achieved using an ADO recordset object as such:
Function MultiByteToBinary(MultiByte)
' 2000 Antonin Foller, http://www.motobit.com
' MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
' Using recordset
Dim RS, LMultiByte, Binary
Const adLongVarBinary = 205
Set RS = CreateObject("ADODB.Recordset")
LMultiByte = LenB(MultiByte)
If LMultiByte>0 Then
RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
RS.Open
RS.AddNew
RS("mBinary").AppendChunk MultiByte & ChrB(0)
RS.Update
Binary = RS("mBinary").GetChunk(LMultiByte)
End If
MultiByteToBinary = Binary
End Function
Hopefully this will help someone else as well.

Let ADODB.Stream do your heavy lifting, this assumes you already have saved the file to disk. These are the functions for BASE64 I use, I'm not 100% sure where I originally got them.
private function readBytes(file)
dim inStream
' ADODB stream object used
set inStream = WScript.CreateObject("ADODB.Stream")
' open with no arguments makes the stream an empty container
inStream.Open
inStream.type= TypeBinary
inStream.LoadFromFile(file)
readBytes = inStream.Read()
end function
private function encodeBase64(bytes)
dim DM, EL
Set DM = CreateObject("Microsoft.XMLDOM")
' Create temporary node with Base64 data type
Set EL = DM.createElement("tmp")
EL.DataType = "bin.base64"
' Set bytes, get encoded String
EL.NodeTypedValue = bytes
encodeBase64 = EL.Text
end function
private function decodeBase64(base64)
dim DM, EL
Set DM = CreateObject("Microsoft.XMLDOM")
' Create temporary node with Base64 data type
Set EL = DM.createElement("tmp")
EL.DataType = "bin.base64"
' Set encoded String, get bytes
EL.Text = base64
decodeBase64 = EL.NodeTypedValue
end function
private Sub writeBytes(file, bytes)
Dim binaryStream
Set binaryStream = CreateObject("ADODB.Stream")
binaryStream.Type = adTypeBinary
'Open the stream and write binary data
binaryStream.Open
binaryStream.Write bytes
'Save binary data to disk
binaryStream.SaveToFile file, adSaveCreateOverWrite
End Sub

Related

Classic ASP file upload issue

I am trying to upload a csv file then read it line by line and pass it to my Database. I have a issue on file upload I could see that whenever I upload a file an extra number gets added to a column in my csv and due to this my code fails. I could see that the file gets saved in the expected location and when I opened it I could see an extra number which I never added. What could be the reason for this?
Here is my code for uploading the CSV file and reading it and using a loop I'm iterating the values in the csv file and storing the values in my variables which is then passed to a method to store in DB.
<HTML>
<HEAD>
<!--#include file="clsUpload.asp"-->
<!-- #include file = "Bin/includes/GenFunctions.asp" -->
<!-- #include file = "Bin/includes/HeaderFooter.asp" -->
</HEAD>
<title>CMTL Entry File Upload</title>
<%showHeader%>
<BODY text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<FORM ACTION = "clsUploadtest.asp" ENCTYPE="multipart/form-data" METHOD="POST">
File Name: <INPUT TYPE=FILE NAME="txtFile"><P>
<INPUT TYPE = "SUBMIT" NAME="cmdSubmit" VALUE="SUBMIT">
</FORM><P>
<%
'Declare the form variables
Dim intRecordId
Dim strRecordId
Dim strAction
Dim strInputDate
Dim strPayer
Dim strAmount
Dim strTransType
Dim strPayee
Dim strAddRemarks
Dim strComments
Dim strAccNo
Dim strPolicyNo
Dim strBranchConfDate
Dim strConfBy
Dim strSheetUpdDate
Dim strMailUpdDate
Dim strUploadTime
Dim strUploadId
Dim strStatus
Dim strLastMdfdDate
Dim strLastMdfdId
Dim lineData
Dim code
Dim name
Dim mail
Dim id
Dim price
Dim amount
Dim MyArray
Dim i
i = 0
set obj = Server.CreateObject("AC_FI.mMTL")
If err.number <> 0 Then
RaiseGenError objCMTL,"Error while creating the object "
Response.End
end if
set o = new clsUpload
if o.Exists("cmdSubmit") then
'get client file name without path
sFileSplit = split(o.FileNameOf("txtFile"), "\")
sFile = sFileSplit(Ubound(sFileSplit))
o.FileInputName = "txtFile"
o.FileFullPath = Server.MapPath(".") & "\entry\" & sFile
o.save
if o.Error = "" then
response.write "Success. File saved to " & o.FileFullPath
else
response.write "Failed due to the following error: " & o.Error
end if
set fso = Server.CreateObject("Scripting.FileSystemObject")
set fs = fso.OpenTextFile(Server.MapPath("entry/" & sFile), 1, False)
Do While Not fs.AtEndOfStream
lineData = fs.ReadLine
'lineData = replace(lineData,chr(13),",")
'lineData = replace(lineData,chr(34),"")
MyArray = Split(lineData , ",")
strRecordId=MyArray(0)
strInputDate=MyArray(1)
strPayer=MyArray(2)
strAmount=MyArray(3)
strTransType=MyArray(4)
strPayee=MyArray(5)
strAddRemarks=MyArray(6)
strComments=MyArray(7)
strAccNo=MyArray(8)
strPolicyNo=MyArray(9)
strBranchConfDate=MyArray(10)
strConfBy=MyArray(11)
strSheetUpdDate=MyArray(12)
strMailUpdDate=MyArray(13)
strUploadTime=MyArray(14)
strUploadId=MyArray(15)
strStatus=MyArray(16)
strRecordId = convertNullString(strRecordId)
strAction = convertNullString(strAction)
strInputDate = convertNullDate(strInputDate)
strPayer = convertNullString(strPayer)
strAmount = convertNullString(strAmount)
strTransType = convertNullString(strTransType)
strPayee = convertNullString(strPayee)
strAddRemarks = convertNullString(strAddRemarks)
strComments = convertNullString(strComments)
strAccNo = convertNullString(strAccNo)
strPolicyNo = convertNullString(strPolicyNo)
strBranchConfDate = convertNullDate(strBranchConfDate)
strConfBy = convertNullString(strConfBy)
strSheetUpdDate = convertNullDate(strSheetUpdDate)
strMailUpdDate = convertNullDate(strMailUpdDate)
strUploadTime = convertNullDate(strUploadTime)
strUploadId = convertNullString(strUploadId)
strStatus = convertNullString(strStatus)
intRecordId = obj.InsertData(strInputDate,strPayer,strAmount,strTransType,strPayee,strAddRemarks,_
strComments,strAccNo,strPolicyNo,strBranchConfDate,strConfBy,strSheetUpdDate,_
strMailUpdDate,strUploadTime,strUploadId,strStatus, pErrorcode)
i=i+1
Loop
fs.close()
set fs = nothing
set fso = nothing
end if
set o = nothing
%>
<%showFooter%>
</BODY>
</HTML>
this is the clsupload.asp file that I have used for file upload
<%
' ------------------------------------------------------------------------------
' Container of Field Properties
Class clsField
Public FileName
Public ContentType
Public Value
Public FieldName
Public Length
Public BinaryData
End Class
' ------------------------------------------------------------------------------
Class clsUpload
' ------------------------------------------------------------------------------
Private nFieldCount
Private oFields()
Private psFileFullPath
Private psError
Private psFileInputName
' ------------------------------------------------------------------------------
Public Property Get Count()
Count = nFieldCount
End Property
' ------------------------------------------------------------------------------
Public Default Property Get Field(ByRef asFieldName)
Dim lnLength
Dim lnIndex
lnLength = UBound(oFields)
If IsNumeric(asFieldName) Then
If lnLength >= asFieldName And asFieldName > -1 Then
Set Field = oFields(asFieldName)
Else
Set Field = New clsField
End If
Else
For lnIndex = 0 To lnLength
If LCase(oFields(lnIndex).FieldName) = LCase(asFieldName) Then
Set Field = oFields(lnIndex)
Exit Property
End If
Next
Set Field = New clsField
End If
End Property
' ------------------------------------------------------------------------------
Public Function Exists(ByRef avKeyIndex)
Exists = Not IndexOf(avKeyIndex) = -1
End Function
' ------------------------------------------------------------------------------
Public Property Get ValueOf(ByRef avKeyIndex)
Dim lnIndex
lnIndex = IndexOf(avKeyIndex)
if lnIndex = -1 Then Exit Property
ValueOf = oFields(lnIndex).Value
End Property
' ------------------------------------------------------------------------------
Public Property Get FileNameOf(ByRef avKeyIndex)
Dim lnIndex
lnIndex = IndexOf(avKeyIndex)
if lnIndex = -1 Then Exit Property
FileNameOf = oFields(lnIndex).FileName
End Property
' ------------------------------------------------------------------------------
Public Property Get LengthOf(ByRef avKeyIndex)
Dim lnIndex
lnIndex = IndexOf(avKeyIndex)
if lnIndex = -1 Then Exit Property
LengthOf = oFields(lnIndex).Length
End Property
' ------------------------------------------------------------------------------
Public Property Get BinaryDataOf(ByRef avKeyIndex)
Dim lnIndex
lnIndex = IndexOf(avKeyIndex)
if lnIndex = -1 Then Exit Property
BinaryDataOf = oFields(lnIndex).BinaryData
End Property
' ------------------------------------------------------------------------------
Private Function IndexOf(ByVal avKeyIndex)
Dim lnIndex
If avKeyIndex = "" Then
IndexOf = -1
ElseIf IsNumeric(avKeyIndex) Then
avKeyIndex = CLng(avKeyIndex)
If nFieldCount > avKeyIndex And avKeyIndex > -1 Then
IndexOf = avKeyIndex
Else
IndexOf = -1
End If
Else
For lnIndex = 0 To nFieldCount - 1
If LCase(oFields(lnIndex).FieldName) = LCase(avKeyIndex) Then
IndexOf = lnIndex
Exit Function
End If
Next
IndexOf = -1
End If
End Function
' ------------------------------------------------------------------------------
Public Property Let FileFullPath(sValue)
psFileFullPath = sValue
End Property
'___________________________________________________________________________________
Public Property Get FileFullPath()
FileFullPath = psFileFullPath
End Property
' ------------------------------------------------------------------------------
Public Property Let FileInputName(sValue)
psFileInputName = sValue
End Property
' -------------------- ----------------------------------------------------------
Public Function Save()
if psFileFullPath <> "" and psFileInputName <> "" then
'Save to connectionless client side recordset, write to stream,
'and persist stream.
'would think you should be able to write directly to
'stream without recordset, but I could not get that to work
On error resume next
binData = o.BinaryDataOf(psFileInputName)
set rs = server.createobject("ADODB.RECORDSET")
rs.fields.append "FileName", 205, LenB(binData)
rs.open
rs.addnew
rs.fields(0).AppendChunk binData
if err.number = 0 then
set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = 1
objStream.Open
objStream.Write rs.fields("FileName").value
objStream.SaveToFile psFileFullPath, 2
objStream.close
set objStream = Nothing
ENd if
rs.close
set rs = nothing
psError = Err.Description
else
psError = "One or more required properties (FileFullPath and/or FileInputName) not set"
End If
End Function
Public Property Get Error()
Error = psError
End Property
' ------------------------------------------------------------------------------
Public Property Get ContentTypeOf(ByRef avKeyIndex)
Dim lnIndex
lnIndex = IndexOf(avKeyIndex)
if lnIndex = -1 Then Exit Property
ContentTypeOf = oFields(lnIndex).ContentType
End Property
' ------------------------------------------------------------------------------
Private Sub Class_Terminate()
Dim lnIndex
For lnIndex = 0 To nFieldCount - 1
Set oFields(0) = Nothing
Next
End Sub
' ------------------------------------------------------------------------------
Private Sub Class_Initialize()
Dim lnBytes ' Bytes received from the client
Dim lnByteCount ' Number of bytes received
Dim lnStartPosition ' Position at which content begins
Dim lnEndPosition ' Position at which content ends
Dim loDic ' Contains properties of each
' specific field
' Local dictionary object(s)
' to be appended to class-scope
' dictionary object.
Dim lnBoundaryBytes ' Bytes contained within the current boundary
Dim lnBoundaryStart ' Position at which the current boundary begins
' within the lnBytes binary data.
Dim lnBoundaryEnd ' Position at which the current boundary ends
' within the lnBytes binary data.
Dim lnDispositionPosition
Dim lsFieldName ' Name of the current field being parsed from
' Binary Data
Dim lsFileName ' Name of the file within the current boundary
Dim lnFileNamePosition ' Location of file name within current boundary
Dim loField ' clsField Object
Dim lsValue ' Value of the current field
Dim lsContentType ' ContentType of the binary file (MIME Type)
' Initialize Fields
nFieldCount = 0
ReDim oFields(-1)
' Read the bytes (binary data) into memory
lnByteCount = Request.TotalBytes
lnBytes = Request.BinaryRead(lnByteCount)
'Get the lnBoundaryBytes
lnStartPosition = 1
lnEndPosition = InstrB(lnStartPosition, lnBytes, CStrB(vbCr))
If lnEndPosition >= lnStartPosition Then
lnBoundaryBytes = MidB(lnBytes, lnStartPosition, lnEndPosition - lnStartPosition)
End If
lnBoundaryStart = InstrB(1, lnBytes, lnBoundaryBytes)
' Loop until the BoundaryBytes begin with "--"
Do Until (lnBoundaryStart = InstrB(lnBytes, lnBoundaryBytes & CStrB("--")))
' All data within this boundary is stored within a local dictionary
' to be appended to the class-scope dictionary.
ReDim Preserve oFields(nFieldCount)
nFieldCount = nFieldCount + 1
Set loField = New clsField
lnDispositionPosition = InstrB(lnBoundaryStart, lnBytes, CStrB("Content-Disposition"))
' Get an object name
lnStartPosition = InstrB(lnDispositionPosition, lnBytes, CStrB("name=")) + 6
lnEndPosition = InstrB(lnStartPosition, lnBytes, CStrB(""""))
lsFieldName = CStrU(MidB(lnBytes, lnStartPosition, lnEndPosition - lnStartPosition))
loField.FieldName = lsFieldName
' Get the location fo the file name.
lnFileNamePosition = InstrB(lnBoundaryStart, lnBytes, CStrB("filename="))
lnBoundaryEnd = InstrB(lnEndPosition, lnBytes, lnBoundaryBytes)
'Test if object is a file
If Not lnFileNamePosition = 0 And lnFileNamePosition < lnBoundaryEnd Then
' Parse Filename
lnStartPosition = lnFileNamePosition + 10
lnEndPosition = InstrB(lnStartPosition, lnBytes, CStrB(""""))
lsFileName = CStrU(MidB(lnBytes,lnStartPosition,lnEndPosition-lnStartPosition))
loField.FileName = lsFileName
' Parse Content-Type
lnStartPosition = InstrB(lnEndPosition,lnBytes,CStrB("Content-Type:")) + 14
lnEndPosition = InstrB(lnStartPosition,lnBytes,CStrB(vbCr))
lsContentType = CStrU(MidB(lnBytes,lnStartPosition,lnEndPosition-lnStartPosition))
loField.ContentType = lsContentType
' Parse Content
lnStartPosition = lnEndPosition + 4
lnEndPosition = InstrB(lnStartPosition,lnBytes,lnBoundaryBytes)-2
lsValue = MidB(lnBytes,lnStartPosition,lnEndPosition-lnStartPosition)
loField.BinaryData = lsValue & CStrB(vbNull)
loField.Length = LenB(lsValue)
Else
' Parse Content
lnStartPosition = InstrB(lnDispositionPosition, lnBytes, CStrB(vbCr)) + 4
lnEndPosition = InstrB(lnStartPosition, lnBytes, lnBoundaryBytes) - 2
lsValue = CStrU(MidB(lnBytes,lnStartPosition,lnEndPosition-lnStartPosition))
loField.Value = lsValue
loField.Length = Len(lsValue)
End If
Set oFields(UBound(oFields)) = loField
'Loop to next object
lnBoundaryStart = InstrB(lnBoundaryStart + LenB(lnBoundaryBytes), lnBytes, lnBoundaryBytes)
Set loField = Nothing
Loop
End Sub
' ------------------------------------------------------------------------------
Private Function CStrU(ByRef psByteString)
Dim lnLength
Dim lnPosition
lnLength = LenB(psByteString)
For lnPosition = 1 To lnLength
CStrU = CStrU & Chr(AscB(MidB(psByteString, lnPosition, 1)))
Next
End Function
' ------------------------------------------------------------------------------
Private Function CStrB(ByRef psUnicodeString)
Dim lnLength
Dim lnPosition
lnLength = Len(psUnicodeString)
For lnPosition = 1 To lnLength
CStrB = CStrB & ChrB(AscB(Mid(psUnicodeString, lnPosition, 1)))
Next
End Function
' ------------------------------------------------------------------------------
End Class
' ------------------------------------------------------------------------------
%>
You can see that the file has an extra value added in it and code fails. I have no idea from where this value comes in each time I upload the file. The file in my local machine doesn't have that value. Can anyone help?

VBA - Handling folder name with utf8 characters

I'm using Application.FileDialog(msoFileDialogFolderPicker) to pick a folder and it handles well folders with utf8 names.
But when I try to Debug.Print the result of SelectedItems(1) or save it to a config file or do anything, I loose the accents of the folder.
For example:
Original folder:
"D:\Śākta"
'Debug.Print' or saving into an utf8 file result saves:
"D:\Sakta" (removed all the accents)
The problem is that I try to save the selected folder to a config file and when I try to load it, next time it will of course won't recognize as a real folder because of the missing accents.
How to get the real name of the folder with the accents to be able to save it after, not this "representation" of it?
Update:
Just checked, and even the InputBox kills the accents!
#John Coleman's answer solved the issue switching the file saving to 'ADODB.Stream'
Here is an example of reading and writing config file supporting UTF8:
Public Function fileExists(ByVal fullFilename As String) As Boolean
fileExists = CreateObject("Scripting.FileSystemObject").fileExists(fullFilename)
End Function
Public Function ReadTextFile(ByVal sPath As String) As String
If fileExists(sPath) Then
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Mode = adModeRead
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.LoadFromFile (sPath)
ReadTextFile = fsT.ReadText
fsT.Close
Set fsT = Nothing
Else
ReadTextFile = ""
End If
End Function
Public Function WriteTextFile(ByVal s As String, ByVal sPath As String) As Boolean
Dim objStreamUTF8NoBOM: Set objStreamUTF8NoBOM = CreateObject("ADODB.Stream")
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText s
fsT.Position = 0
fsT.SaveToFile sPath, 2 'Save binary data To disk
fsT.Position = 3
With objStreamUTF8NoBOM
.Type = 1
.Open
fsT.CopyTo objStreamUTF8NoBOM
.SaveToFile sPath, 2
Close
End With
fsT.Close
Set fsT = Nothing
Set objStreamUTF8NoBOM = Nothing
End Function
Function SetSettings(ByVal Keyname As String, ByVal Wstr As String) As String
Dim settingsFileContent
settingsFileContent = ReadTextFile(IniFileName)
Set RE = CreateObject("VBScript.RegExp")
RE.Pattern = Keyname + "=.*"
RE.MultiLine = 1
If RE.Test(settingsFileContent) Then
settingsFileContent = RE.Replace(settingsFileContent, Keyname + "=" + Wstr)
Else
settingsFileContent = settingsFileContent + IIf(Len(settingsFileContent) = 0, "", vbNewLine) + Keyname + "=" + Wstr
End If
WriteTextFile settingsFileContent, IniFileName
SetSettings = Wstr
End Function
Private Function GetSettings(ByVal Keyname As String) As String
Dim settingsFileContent As String
settingsFileContent = ReadTextFile(IniFileName)
Set RE = CreateObject("VBScript.RegExp")
RE.MultiLine = 1
RE.Global = 1
RE.Pattern = "\r"
settingsFileContent = RE.Replace(settingsFileContent, "")
RE.Global = 0
RE.Pattern = "^" + Keyname + "=(.*)"
Set allMatches = RE.Execute(settingsFileContent)
If allMatches.Count <> 0 Then
Debug.Print (Keyname + ": """ + allMatches.Item(0).SubMatches.Item(0) + """")
GetSettings = allMatches.Item(0).SubMatches.Item(0)
Else
GetSettings = ""
End If
End Function

vb.net readalllines fill form replace certain lines coding advice

What I'm trying to accomplish is reading a text file and selecting certain lines to modify by filling in text from a second form. Here is an example the code I'm currently using. What's happening is I'm looking for a line that starts with 718 and then somewhere after that line there will be a line that starts with 720. I need both lines to fill in the second form. The only way I can think of is to just keep adding 1 to the line until it reaches the line I need. I'm still new to this and I'm sure there's an easier way to do this maybe using Try or While but I'm not sure how. Appreciate any help.
Dim lines() As String = File.ReadAllLines(tempsave)
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith("718") Then
If lines(i + 1).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 1).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array(3), FormFill.TextBox1.Text)
lines(i + 1) = lines(i + 1).Replace(array(9), FormFill.TextBox2.Text)
Else
If lines(i + 2).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 2).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array2(3),FormFill.TextBox1.Text)
lines(i + 2) = lines(i + 2).Replace(array(9), FormFill.TextBox2.Text)
End If
End If
End If
Next
Example Data:
Input:
123*test*test*test~
718*test*test*test~
543*test*test*test~
720*test*test*test~
Output:
123*test*test*test~
718*test*test*newdata~
543*test*test*test~
720*test*test*newdata~
Here, try this:
Public Sub Lines()
Dim _
aNextLines,
aAllLines As String()
Dim _
s718Line,
s720Line As String
aAllLines = IO.File.ReadAllLines("D:\Logs\Data.log")
For i As Integer = 0 To aAllLines.Length - 1
If aAllLines(i).StartsWith("718") Then
s718Line = aAllLines(i)
aNextLines = aAllLines.Skip(i + 1).ToArray
s720Line = aNextLines.FirstOrDefault(Function(Line) Line.StartsWith("720"))
' Process data here
End If
Next
End Sub
--UPDATE--
Here's a modified version that both reads and writes:
Public Sub Lines()
Dim oForm As FormFill
Dim _
aNextLines,
aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
oForm = New FormFill
aAllLines = IO.File.ReadAllLines(oForm.FilePath)
s718Line = String.Empty
s720Line = String.Empty
For i718Index = 0 To aAllLines.Length - 1
If aAllLines(i718Index).StartsWith("718") Then
s718Line = aAllLines(i718Index)
aNextLines = aAllLines.Skip(i718Index + 1).ToArray
For i720Index = 0 To aNextLines.Length - 1
If aNextLines(i720Index).StartsWith("720") Then
s720Line = aNextLines(i720Index)
Exit For ' Assumes only one 720 line in the file
End If
Next
Exit For ' Assumes only one 718 line in the file
End If
Next
oForm.TextBox718.Text = s718Line
oForm.TextBox720.Text = s720Line
oForm.TextBox718.Tag = i718Index
oForm.TextBox720.Tag = i720Index
End Sub
Now, in your Save button's Click event handler:
Private Sub SaveButton_Click(Sender As Button, e As EventArgs) Handles SaveButton.Click
Dim aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
s718Line = Me.TextBox718.Text
s720Line = Me.TextBox720.Text
i718Index = Me.TextBox718.Tag
i720Index = Me.TextBox720.Tag
aAllLines = IO.File.ReadAllLines(Me.FilePath)
aAllLines(i718Index) = s718Line
aAllLines(i720Index) = s720Line
IO.File.WriteAllLines(Me.FilePath, aAllLines)
End Sub
That should do it.

Using MailMessage with semi cologn seperation

If I manually put my address in for EmailMessage.To.Add(GetDelimitedField(x, strEmailRep, ";")) It sends me the message just fine. However If I use the code as is below which is using a list that looks like ;email1#mail.com;email2.mail.com
Then it gives an error that email address cannot be blank
Somewhere in GetDelimitedField is erasing addresses. I'm not sure where the problem is actually occurring. Here is all the code involved with this.
strmsg = "LOW STOCK ALERT: Component (" & rsMPCS("MTI_PART_NO") & ") has reached or fallen below it's minimum quantity(" & rsMPCS("MIN_QTY") & ")."
Dim EmailMessage As MailMessage = New MailMessage
EmailMessage.From = New MailAddress("noreply#mail.com")
For x = 1 To GetCommaCount(strEmailRep) + 1
EmailMessage.To.Add(GetDelimitedField(x, strEmailRep, ";"))
Next
EmailMessage.Subject = ("LOW STOCK ALERT!")
EmailMessage.Body = strmsg
EmailMessage.Priority = MailPriority.High
EmailMessage.IsBodyHtml = True
Dim smtp As New SmtpClient("smtp.mycompany.com")
smtp.UseDefaultCredentials = True
smtp.Send(EmailMessage)
Public Function GetCommaCount(ByVal sText As String)
Dim X As Integer
Dim Count As Integer
Dim Look As String
For X = 1 To Len(sText)
Look = Microsoft.VisualBasic.Left(sText, X)
If InStr(X, Look, ";", 1) > 0 Then
Count = Count + 1
End If
Next
GetCommaCount = Count
End Function
Public Function GetDelimitedField(ByRef FieldNum As Short, ByRef DelimitedString As String, ByRef Delimiter As String) As String
Dim NewPos As Short
Dim FieldCounter As Short
Dim FieldData As String
Dim RightLength As Short
Dim NextDelimiter As Short
If (DelimitedString = "") Or (Delimiter = "") Or (FieldNum = 0) Then
GetDelimitedField = ""
Exit Function
End If
NewPos = 1
FieldCounter = 1
While (FieldCounter < FieldNum) And (NewPos <> 0)
NewPos = InStr(NewPos, DelimitedString, Delimiter, CompareMethod.Text)
If NewPos <> 0 Then
FieldCounter = FieldCounter + 1
NewPos = NewPos + 1
End If
End While
RightLength = Len(DelimitedString) - NewPos + 1
FieldData = Microsoft.VisualBasic.Right(DelimitedString, RightLength)
NextDelimiter = InStr(1, FieldData, Delimiter, CompareMethod.Text)
If NextDelimiter <> 0 Then
FieldData = Microsoft.VisualBasic.Left(FieldData, NextDelimiter - 1)
End If
GetDelimitedField = FieldData
End Function
You can split the list easier using string.Split:
Dim strEmails = "a#test.com;b#test.com;c#test.com;"
Dim lstEmails = strEmails.Split(";").ToList()
'In case the last one had a semicolon:
If (lstEmails(lstEmails.Count - 1).Trim() = String.Empty) Then
lstEmails.RemoveAt(lstEmails.Count - 1)
End If
If (lstEmails.Count > 0) Then
lstEmails.AddRange(lstEmails)
End If

system.io.ioexception the process cannot access because it is being used by another process

i am getting this problem in some systems, some systems working properly, here my code is,
Dim fileName As String = "FaultTypesByMonth.csv"
Using writer As IO.StreamWriter = New IO.StreamWriter(fileName, True, System.Text.Encoding.Default) '------------ rao new ----
Dim Str As String
Dim i As Integer
Dim j As Integer
Dim headertext1(rsTerms.Columns.Count) As String
Dim k As Integer = 0
Dim arrcols As String = Nothing
For Each column As DataColumn In TempTab.Columns
arrcols += column.ColumnName.ToString() + ","c
k += 1
Next
writer.WriteLine(arrcols)
For i = 0 To (TempTab.Rows.Count - 1)
For j = 0 To (TempTab.Columns.Count - 1)
If j = (TempTab.Columns.Count - 1) Then
Str = (TempTab.Rows(i)(j).ToString)
Else
Str = (TempTab.Rows(i)(j).ToString & ",")
End If
writer.Write(Str)
Next
writer.WriteLine()
Next
writer.Close()
writer.Dispose()
End Using
Dim FileToDelete As String = Nothing
Dim sd As New SaveFileDialog
sd.Filter = "CSV Files (*.csv)|*.csv"
sd.FileName = "FaultTypesByMonth"
If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
FileCopy(fileName, sd.FileName)
MsgBox(" File Saved in selected path")
FileToDelete = fileName
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
FileToDelete = fileName
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
when i am trying to save this file in desired path, then i am getting this error.
if save in shared folder i am not getting this error
system.io.ioexception the process cannot access because it is being used by another process...
what i am doing wrong,Help me