如何正确关闭流? [英] How to close a stream properly?
问题描述
我被分配了一个任务来编写一个程序,该程序将:
I have been assigned a task to write a program that will:
-
打开文件.
Open a file.
阅读内容.
用另一个单词替换一个特定的单词.
Replace a specific word with another word.
将更改保存到文件.
我肯定知道我的代码可以打开,阅读和替换单词.当我添加将更改保存到文件"-部分时,会发生问题.这是代码:
I know for sure that my code can open, read and replace words. The problem occurs when i add the "Save the changes to the file" - part. Here is the code:
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库尝试了不同的操作,但始终收到相同的错误消息.非常感谢您的帮助.
I get the error message "Sharing violation on path...", which makes me believe that the reading stream do not close properly. I have tried playing around with the structure of my code and tried different things for the .NET library, but i always get the same error message. Any help is much appreciated.
推荐答案
Streams are normally closed by calling Stream.Close() or disposing them.
System.IO
具有从行数组读取或向行数组写入完整文件的方法.这样会将操作缩短为这样:
System.IO
has methods to read or write complete files from/to arrays of lines. This would shorten the operation to something like this:
File.ReadAllLines filePath
|> Array.map (fun line -> line.Replace(needle, replace))
|> fun editedLines -> File.WriteAllLines(filePath, editedLines)
您正在使用什么文档?看看系统的MSDN文档.IO 和类似的MSDN文档,用于.NET/CLR中的各种内容;这些可以迅速回答这样的问题.
What documentation are you using? Have a look at the MSDN documentation for System.IO and the similar MSDN documentations for various things in .NET/the CLR; these answer questions like this one quickly.
这篇关于如何正确关闭流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!