如何使用C#从FTP读取CSV文件

时间:2014-06-16 02:38:52

标签: c# .net csv ftp c#-3.0

我能够通过身份验证,但我不知道如何阅读CSV文件。通常从硬盘驱动器链接我这样读。

string[] allLines = System.IO.File.ReadAllLines(@"D:\CSV\data.csv");

但我如何从ftp中读取。我的Ftp路径就像ftp://ftp.atozfdc.com.au/data.csv 这是我通过ftp身份验证的代码。

String ftpserver = "ftp://ftp.atozfdc.com.au/data.csv";
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
reqFTP.UsePassive = false;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

3 个答案:

答案 0 :(得分:7)

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//use the response like below
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string[] allLines = reader.ReadToEnd().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

答案 1 :(得分:3)

看看这个link


TextFieldParser位于Microsoft.VisualBasic.FileIO命名空间中。因此,您需要添加对Microsoft.VisualBasic.dll

的引用
String path = @"D:\CSV\data.csv";

using (TextFieldParser parser = new TextFieldParser(path))
{
    parser.SetDelimiters(new string[] { "," });
    parser.HasFieldsEnclosedInQuotes = true;

    // if you want to skip over header line., uncomment line below
    // parser.ReadLine();

    while (!parser.EndOfData)
    {
        string[] fields = parser.ReadFields();
        column1 = fields[0];
        column2 = fields[1];
        column3 = int.Parse(fields[2]);
        column4 = double.Parse(fields[3]);
    }
}

我建议您将文件下载到临时位置,然后使用临时文件路径解析CSV。

但如果您不想创建临时文件,请尝试使用ResponseStream

示例:

String ftpserver = "ftp://ftp.atozfdc.com.au/data.csv";
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
reqFTP.UsePassive = false;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();


Stream responseStream = response.GetResponseStream();
// use the stream to read file from remote location

using (TextFieldParser parser = new TextFieldParser(responseStream))
{
    // usual csv reader implementation
}

responseStream.Close();
response.Close(); //Closes the connection to the server

答案 2 :(得分:0)

ftp://ftp.atozfdc.com.au/data.csv这是你的ftp文件路径。你还在寻找什么?如果您想阅读该文件,请使用

StreamReader reader = new StreamReader(responseStream);
string[] allLines = reader.ReadToEnd().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)