C#如何读取网络地址上的csv文件
时间: 2024-10-24 10:15:32 浏览: 12
使用C#读取CSV文件
在C#中,你可以使用`System.IO.Packaging`和`System.IO.Compression`命名空间来读取网络上CSV文件,尤其是在文件是压缩(如.gz、.zip等)的情况下。以下是一个基本示例,展示如何使用`HttpClient`下载文件并解压后读取CSV内容:
```csharp
using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
public class CsvReader
{
private static async Task<string> DownloadFileAsync(string url)
{
using HttpClient client = new HttpClient();
byte[] bytes = await client.GetByteArrayAsync(url);
// 检查是否是压缩文件
if (bytes.Length > 0 && bytes[0] == 0x1f && bytes[1] == 0x8b) // gzip signature
{
using MemoryStream memStream = new MemoryStream(bytes);
using GZipStream decompressStream = new GZipStream(memStream, CompressionMode.Decompress);
using StreamReader reader = new StreamReader(decompressStream);
return reader.ReadToEnd();
}
else
{
// 如果不是压缩文件,则直接处理字节数组
using MemoryStream memStream = new MemoryStream(bytes);
using StreamReader reader = new StreamReader(memStream);
return reader.ReadToEnd();
}
}
public static void ReadCsvFromUrl(string url)
{
string csvContent = await DownloadFileAsync(url);
// 现在可以解析csvContent
using (var reader = new StringReader(csvContent))
using (var csv = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))
{
csv.TextFieldType = FileFieldType.Delimited;
csv.SetDelimiters(",");
while (!csv.HasMoreRecords)
{
string[] fields = csv.ReadFields();
Console.WriteLine(string.Join(",", fields));
}
}
}
public static void Main(string[] args)
{
string csvUrl = "http://example.com/data.csv"; // 替换为你需要的URL
ReadCsvFromUrl(csvUrl);
}
}
```
阅读全文