简体   繁体   中英

How to write to the the beginning of file in F#

I need to write a running number - at the beginning of existing files. All I have been able to do so far is to write to the end of each file. Any help please?

How about (warning! untested code):

open System.IO
File.ReadAllText("c:\\old.txt")
    |> fun s -> let r = new StreamReader(s)
                let data = r.ReadToEnd
                r.Close()
                s.Close()
                data

let writeStringToFile d =
    (File.OpenWrite("c:\\new.txt"), d)
    |> fun ((s : FileStream), (d : string)) -> let r = new StreamWriter(s)
                                               r.WriteLine("new data")
                                               r.Write(d)
                                               r.Close()
                                               s.Close()

getStringFromFile()
|> writeStringToFile

EDIT:

Much better solution:

File.WriteAllText("c:\\new.txt", "new Text" + File.ReadAllText("c:\\old.txt"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM