Folder item question

Hi all!

Could I ask for some guidance?

I am trying to have a textarea display the contents of a .txt file that has been created in the project folder called “List.txt” (Without an OpenDialog).

In a buttons “Action” event I have the following code.

Var f As FolderItem
f = New FolderItem("List.txt")

if f.Exists then
  TextArea1.text = f
end if

I know this code is probably very wrong (as it doesn’t work). I am still trying to grasp folderitems and the such.

I’m running xojo in windows using xojo 2021 R2.1

Thank you all kindly in advance!

Robin

Try it this way:

Var f As FolderItem = FolderItem.ShowOpenFileDialog("text") // as defined in File Type Sets Editor
If f <> Nil Then
  If f.Exists Then
    // Be aware that TextInputStream.Open could raise an exception
    Var t As TextInputStream
    Try
      t = TextInputStream.Open(f)
      t.Encoding = Encodings.MacRoman
      TextArea1.Value = t.ReadAll
    Catch e As IOException
      MessageBox("Error accessing file.")
    End Try
    t.Close
  End If
End If

This is from a documentation example. Of course, you have to change some things for your project. Probably, setting encodings to UTF8, or the file name accordingly.

1 Like

Thank you Rainer!

I came across this in the documentation, Is there anyway to display the text without opening the file using the ShowOpenFileDialog?

Yes, if you know the file name you can just use FolderItem.Child:

Var docFile As FolderItem = SpecialFolder.Desktop.Child(“Docs”).Child(“Current”).Child(“MyFile.txt”)

No, that ain’t safe anymore. According to Apple, if you use macOS.

Is that really from the docs? I’ve removed the 2 nested ifs. Without the nesting the code is easier to read:

Var f As FolderItem = FolderItem.ShowOpenFileDialog("text") // as defined in File Type Sets Editor
If f = Nil or not f.exists Then return
    // Be aware that TextInputStream.Open could raise an exception
Var t As TextInputStream
Try
    t = TextInputStream.Open(f)
    t.Encoding = Encodings.MacRoman
    TextArea1.Value = t.ReadAll
   t.Close
Catch e As IOException
      MessageBox("Error accessing file.")
End Try
 

t.close must be in the try/catch. If there is an exception t might be nil and closing the TextInputStream would make a NilObjectException.

2 Likes

you can add a build step copy files to windows build settings (context menu)
with target to ressources folder.
drag & drop your file into.

than you load this file at runtime

Var f As FolderItem = SpecialFolder.Resources.Child("file.txt")

Var st As TextInputStream = TextInputStream.Open(f)

TextArea1.Text = st.ReadAll

st.Close
1 Like

You want something akin to:


f = new FolderItem ("/path/to/your/List.txt", FolderItem.PathModes.Native)

.
and as others have pointed out, you actually need to read the file.

1 Like