我被分配了一项任务来编写一个程序,该程序将:
打开一个文件。
阅读内容。
将特定单词替换为另一个单词。
保存对文件的更改。
我确信我的代码可以打开、读取和替换单词。当我添加“保存对文件的更改”部分时,出现问题。这是代码:
open System.IO
//Getting the filename, needle and replace-word.
System.Console.WriteLine "What is the name of the file?"
let filename = string (System.Console.ReadLine ())
System.Console.WriteLine "What is your needle?"
let needle = string (System.Console.ReadLine ())
System.Console.WriteLine "What you want your needle replaced with?"
let replace = string (System.Console.ReadLine ())
//Saves the content of the file
let mutable saveLine = ""
//Opens a stream to read the file
let reader = File.OpenText filename
//Reads the file, and replaces the needle.
let printFile (reader : System.IO.StreamReader) =
while not(reader.EndOfStream) do
let line = reader.ReadLine ()
let lineReplace = line.Replace(needle,replace)
saveLine <- saveLine + lineReplace
printfn "%s" lineReplace
//Opens a stream to write to the file
let readerWrite = File.CreateText(filename)
//Writes to the file
let editFile (readerWrite : System.IO.StreamWriter) =
File.WriteAllText(filename,saveLine)
printf "%A" (printFile reader)
我收到错误消息“共享路径上的冲突...”,这使我相信读取流没有正确关闭。我尝试过修改我的代码结构,并对 .NET 库尝试不同的操作,但我总是收到相同的错误消息。任何帮助深表感谢。
流通常通过调用关闭Stream.Close() https://msdn.microsoft.com/en-us/library/system.io.stream.close(v=vs.110).aspx或处置它们。
System.IO
具有从行数组读取或写入完整文件的方法。这会将操作缩短为如下所示:
File.ReadAllLines filePath
|> Array.map (fun line -> line.Replace(needle, replace))
|> fun editedLines -> File.WriteAllLines(filePath, editedLines)
您使用什么文档?看一下System.IO 的 MSDN 文档 https://msdn.microsoft.com/en-us/library/system.io(v=vs.110).aspx以及有关 .NET/CLR 中各种内容的类似 MSDN 文档;这些可以快速回答诸如此类的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)