这两天看了看F#,觉得还是非常容易上手的,顺手写了个一个非常简单的下载文件的程序。
open System.Net
open System.IO
let getStreamData (stream : Stream) =
seq {
let buffer = Array.zeroCreate(1500)
let count = ref 0
while (count := stream.Read(buffer, 0, buffer.Length); !count) > 0 do
//printfn "%d" !count
yield (buffer, 0, !count)
}
let downloadFile (url : string) (file : string) =
let req = WebRequest.Create(url)
use rsp = req.GetResponse()
use rspStream = rsp.GetResponseStream()
use fileStream = File.Create(file)
rspStream
|> getStreamData
|> Seq.iter fileStream.Write
downloadFile "http://dlc2.pconline.com.cn/filedown.jsp?dlid=51901&linkid=6524421" @"r:\test.zip"
由于目前对F#还是管中窥豹,这个程序中难免还有不少需要改进的地方,希望大家多提意见。