如何使用c#从FTP读取CSV文件
本文关键字:读取 CSV 文件 FTP 何使用 | 更新日期: 2023-09-27 18:08:40
我能够通过身份验证,但我不确定如何读取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();
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);
看看这个链接
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
ftp://ftp.atozfdc.com.au/data.csv这是您的FTP文件路径。你还在找什么?如果要读取文件,请使用
StreamReader reader = new StreamReader(responseStream);
string[] allLines = reader.ReadToEnd().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)