F#-fileReplace,覆盖txt中的单词,但运行时会覆盖txt中的现有内容 开放系统 //帮助功能 让fileReplace文件名指针替换= 让replaceIn(读卡器:System.IO.StreamReader)指针(replace:String)= 而不是(reader.EndOfStream)这样做 设mutable allText=reader.ReadToEnd() allText

F#-fileReplace,覆盖txt中的单词,但运行时会覆盖txt中的现有内容 开放系统 //帮助功能 让fileReplace文件名指针替换= 让replaceIn(读卡器:System.IO.StreamReader)指针(replace:String)= 而不是(reader.EndOfStream)这样做 设mutable allText=reader.ReadToEnd() allText,replace,f#,stream,overwrite,opentext,Replace,F#,Stream,Overwrite,Opentext,您编写的replaceIn函数没有任何作用。让我们把这个分开: 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 = reade

您编写的
replaceIn
函数没有任何作用。让我们把这个分开:

    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
首先要注意的是,此函数返回
单位
,这意味着无论文件内容如何,
newText
始终具有
()
的值。这意味着您总是不向文件中写入任何内容

此外,您的循环是多余的。您正在读取到流的末尾,但循环直到流的末尾-此循环是不必要的。无论如何,也无法观察循环的结果,因为创建用于存储结果的可变变量位于循环内部


那么,让我们看看另一种选择:

val replaceIn :  reader:System.IO.StreamReader -> needle:string -> replace:string -> unit
如您所见,您甚至不需要创建读卡器,只需在
System.IO.File
中创建helper函数即可

val replaceIn :  reader:System.IO.StreamReader -> needle:string -> replace:string -> unit
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)