Nil Object error ?

Hi,
In my window’s open event, I am trying to check if a .txt file exists - if so, open it into a textfield - if not, create it and write a line of text.

I have the code below, but I keep getting a nil object exception. Could someone please help me as to what I am doing wrong?
Thank you.

[code] Dim f As FolderItem = SpecialFolder.ApplicationData.Child(“Snippet Data”).Child(“DevNotes.txt”)
Dim tis As TextInputStream

If f <> Nil and f.Exists then
tis=TextInputStream.Open(f)
tis.Encoding = Encodings.UTF8
DevNotesField.text = tis.ReadAll
tis.Close

else
Dim tos As TextOutputStream
tos = TextOutputStream.Create(f)
tos.WriteLine(“Dev Notes”)
tos.Close

End[/code]

If f is nil then the folder “Snippet Data” is likely not present. Generally a folderitem = Nil indicates a path error so

Dim f As FolderItem = SpecialFolder.ApplicationData.Child("Snippet Data").Child("DevNotes.txt")

Should be

Dim f As FolderItem = SpecialFolder.ApplicationData.Child("Snippet Data") If Not f.Exists Then f.CreateAsFolder // Creates the "Snippet Data" folder if not present f = f.Child("DevNotes.txt")

Richard - I adapted your code like this:

  Dim f As FolderItem = SpecialFolder.Desktop.Child("DevNotes.txt")
  Dim tis As TextInputStream
  
  If f <> Nil and f.Exists then
    tis=TextInputStream.Open(f)
    tis.Encoding = Encodings.UTF8
    DevNotesField.text = tis.ReadAll
    tis.Close
    
  else
    Dim tos As TextOutputStream
    tos = TextOutputStream.Create(f)
    tos.WriteLine("Dev Notes")
    tos.Close
    
  End

And it worked fine. Here’s my sample project.

So my guess is that either:

The referenced directory doesn’t exist (“Snippet Data”)

OR

You don’t have write permissions to it

What line is throwing the error? What object is NIL?

Anthony

Ok,
embarrassingly I misspelt the folders name :slight_smile:

My code now looks like this:

[code] Dim f As FolderItem = SpecialFolder.ApplicationData.Child(“Snippets Data”).Child(“DevNotes.txt”)
Dim tis As TextInputStream

If f <> Nil and f.Exists then
tis=TextInputStream.Open(f)
tis.Encoding = Encodings.UTF8
DevNotesField.text = tis.ReadAll
tis.Close

else
DevNotesField.text = “Dev Notes:” + EndOfLine + EndOfLine
Dim tos As TextOutputStream
tos = TextOutputStream.Create(f)
tos.WriteLine(“Dev Notes:”)
tos.Close

End[/code]

My code now works perfectly!
Does my code look efficient enough, or do you guys have any advice to optimise my code?

Thank you both for all your help :slight_smile:

Of course! I thought it was likely the directory name being wrong. Watch out for spaces too. I’ve done things like this:

“My  Folder” 

when I meant:

“My Folder"

Difference? Two spaces in the first string. Whoops!!

(edit - had to put sample names in code tags or ESOTalk was removing extra space!)

Thank You!