I am able to pass the authentication but i am not sure how can i read a CSV file. Link normally from a hard drive i am reading like this .
string[] allLines = System.IO.File.ReadAllLines(@"D:\CSV\data.csv");
But how can i read from the ftp . My Ftp path is like that ftp://ftp.atozfdc.com.au/data.csv Here is my code to pass ftp authentication.
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);
Have a look at this link
TextFieldParser
is in the Microsoft.VisualBasic.FileIO
namespace. Hence you need to add reference to 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]);
}
}
I would suggest you to download the file to a temporary location, and then use the temp file path to parse the CSV.
but if you do not want to create temp file then try using the ResponseStream
Example:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With