### Read and Write Textfile

Read and write the content of TextFiles using File.
Reference: http://www.b4x.com/b4j/help/files.html#file
Read the content of a TextFile to a String
Solution 1
'Read the content of a textfile to a string. A list and stringbuilder is used to ensure proper CRLF handling.
'Returns File content as string or error message
'Example:fx.Clipboard.SetString(File2String(File.DirApp, "myfile.txt"))
`Sub File2String(folder As String, filename As String) As String
Dim result As String = ""
Dim sb As StringBuilder
sb.Initialize
Try
Dim l As List = File.ReadList(folder,filename)
For i = 0 To l.Size - 1
sb.Append(l.Get(i) & CRLF)
Next
result = sb.ToString
Catch
result = LastException.Message
End Try
Return result
End Sub`
Solution 2
'Read the content of a textfile to a string.
'Parameter: dir as string, file as string
'Example:
'Log(File2String(File.DirApp, "tptest.txt"))
`Sub File2String(d As String, f As String) As String
Dim result As String = ""
Try
result = File.ReadString(d, f)
Catch
Log(LastException.Message)
End Try
Return result
End Sub`
Write a String to a TextFile
'Parameter: dir as string, file as string, s as string
'Example:
'Log(String2File(File.DirApp, "tptest2.txt", "L1"&CRLF&"L2"))
`Sub String2File(d As String, f As String, s As String) As Boolean
Dim result As Boolean = True
Try
File.WriteString(d, f, s)
Catch
result = False
Log(LastException.Message)
End Try
Return result
End Sub`

Changed: , Category: Files, File: T6C193M1389.htm, ID: 1389