0

I am trying to get a file path via SaveFileDailog and then use a StreamWriter to actually create the file and then write the data. But it does not work. I get an exception saying the file is in use by another process. Which doesn't make any sense, since I have disposed of the SaveFileDialog and ran garbage collection...

This is my code so far.

let dialog = new SaveFileDialog()
let result = dialog.ShowDialog()
let file =
        match result with
        | DialogResult.OK ->dialog.OpenFile()
        | _ ->  failwith "cancel"

let path = dialog.FileName
dialog.Dispose()
let result = null
let dialog = null
GC.Collect()
let writer = (File.CreateText(path))

I am sure it is just something silly, but I would still like help with it.

Alexander Ryan Baggett
  • 2,347
  • 4
  • 34
  • 61

1 Answers1

2

The main problem with this code is the call to dialog.OpenFile(). Why do you do it? Do you know what it does?

As it happens (and is stated in the documentation), OpenFile() actually opens the file and returns you a Stream instance ready to use. For some reason, however, you throw away this stream and try to create your own, which, of course, fails, because the file is already open.

So the correct code would be this:

let getStreamForSaving() =
  use dialog = new SaveFileDialog()
  match dialog.ShowDialog() with
  | DialogResult.OK -> dialog.OpenFile()
  | _ ->  failwith "cancel"

(note the use of use - the F# way of automatically calling .Dispose when needed)

That's it, no dancing around with .Dispose and null required.

And speaking of null. The two lines that, as you apparently assume, assign null to the variables dialog and result, don't actually do that. In F# all let-bound values are immutable (as in, cannot be mutated), unless you explicitly specify otherwise. And even if you do specify otherwise, mutating values is done with the "destructive update operator" <-.

What your code does instead is create new values named dialog and result - completely separate, not at all related to the old ones. If you look carefully, you'll see that they even have different types. This is called "shadowing" - a very useful thing, but nothing to do with mutability or garbage collection.

Community
  • 1
  • 1
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172