replacef#streamoverwriteopentext

F# - fileReplace, overwriting words in txt, but when running it overwrites exisiting content in txt


    open System
//helpfunction
let fileReplace filename needle replace =
  let replaceIn (reader:System.IO.StreamReader) needle (replace: String) =
    while not(reader.EndOfStream) do
      let mutable allText = reader.ReadToEnd()
      allText <- allText.Replace(needle, replace)
    reader.Close()

  //start
  let reader = System.IO.File.OpenText filename
  let newText = replaceIn reader needle replace
  let writer = System.IO.File.CreateText filename
  writer.Write newText ; writer.Close()

// testing
let filename = @".\abc.txt"
let needle = "med"
let replace = "MED"
fileReplace filename needle replace

I've experimented a bunch moving reader.Close() around, but with no results yet. I know that if I insert printfn "%A" allText under reader.Close(), it prints the correct result, so I suspect its when I call writer that it goes wrong. I need the code to replace med, with MED in abc.txt. but instead it leaves an empty abc.txt


Solution

  • The replaceIn function that you've written doesn't do anything. Let's separate this out:

    let replaceIn (reader:System.IO.StreamReader) needle (replace: string) =
        while not(reader.EndOfStream) do
            let mutable allText = reader.ReadToEnd()
            allText <- allText.Replace(needle, replace)
        reader.Close()
    

    First, look at the type of this function:

    val replaceIn :  reader:System.IO.StreamReader -> needle:string -> replace:string -> unit
    

    The first thing to note is that this function returns unit, that means newText always has a value of (), regardless of file content. That means you are always writing nothing to your file.

    Furthermore, your loop is superfluous. You are reading to the end of the stream yet looping until the end of the stream - this loop is unnecessary. There is also no way to observe the results of the loop anyway because the mutable variable you are creating to store the result in is inside the loop.


    So, let's look at an alternative:

    let fileReplace filename (needle : string) (replace : string) =
        let allText = System.IO.File.ReadAllText filename
        let newText = allText.Replace(needle, replace)
        System.IO.File.WriteAllText(filename, newText)
    

    As you can see, you don't even need to create the readers, you can just the helper functions in System.IO.File.