如何将Web服务流数据写入本地目录中的文件

时间:2014-12-24 16:37:50

标签: c#

当我调用Web服务时,它会以CSV格式输出数据。

致电网络服务:

https://www.rate-exchange.com/rates/api/v1/rates/USD.csv?quote=EUR&quote=GBP&fields=all

其输出如下:

base_currency,currency,date,bid,ask,midpoint,high_bid,high_ask,low_bid,low_ask
USD,EUR,2014-12-23T21:00:00+0000,0.81875,0.81885,0.81880,0.82199,0.82208,0.81658,0.81667
USD,GBP,2014-12-23T21:00:00+0000,0.64275,0.64284,0.64280,0.64569,0.64577,0.64064,0.64071

问题: 我可以在C#中使用代码段将输出流写入rate.csv的文件c:\temp吗?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果服务返回简单字符串:

string data = client.GetCsv();
using(StreamWriter sw = new StreamWriter(File.OpenWrite("c:\csv.txt"))
{
    sw.WriteLine(data);
}

如果你的csv文件没有新的行号:

string lines[] = data.split(Environment.NewLine);
using(StreamWriter sw = new StreamWriter(File.OpenWrite("c:\csv.txt"))
{
    for(int i = 0; i < lines.Length; i++)
    {
        sw.WriteLine(lines[i]);
    }
}