I have to upload 1000 to 1500 images at a time on server.. Code is as follows.
public void add_data()
{
DataSet ds = new DataSet();
ds = get_Data();
int p = 0;
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
int cnt = ds.Tables[0].Rows.Count;
while (cnt > 0)
{
string url = Convert.ToString(ds.Tables[0].Rows[p]["image_name"]);
string imagename = url.Substring(url.LastIndexOf('/') + 1);
string file_name = imagename;
save_file_from_url(file_name, url);
p++;
cnt = cnt - 1;
}
}
}
}
public void save_file_from_url(string file_name, string url)
{
if (!File.Exists(file_name))
{
try
{
byte[] imgcontent;
//Convert live images into byte array to pass it for ftp server
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
imgcontent = br.ReadBytes(500000);
br.Close();
}
response.Close();
string CompleteDPath = "www.xyz.com";
string UName = "abc";
string PWD = "pwd";
WebRequest reqObj = WebRequest.Create(CompleteDPath + file_name);
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
reqObj.Credentials = new NetworkCredential(UName, PWD);
reqObj.GetRequestStream().Write(imgcontent, 0, imgcontent.Length);
reqObj = null;
}
catch (Exception ex)
{
lblmessage.ForeColor = System.Drawing.Color.Red;
lblmessage.Text = ex.Message;
}
}
}
But it gives following error that
The following error was encountered:
Read Timeout
The system returned:
[No Error]
A Timeout occurred while waiting to read data from the network. The network or server may be down or congested. Please retry your request.
Your cache administrator is webmaster.
What should i use? Please help!
please close the network/database connection after one image is uploaded. The read time out is because the connection is ON for too much time and it gets timed out.
Or you can make a query with commas like
Insert multiple rows with one statement
Related
I created an application for the Pharmacy management system using mysql and c#. They have the databases on Local and Remote server also. Basically all records are stored on local database. Then after the newly created records should be uploaded to the remote server using JSon file. I also have the code to execute the Json file data to remote server using php. I have the newly records on Desktop using json file.
JSon file export coding :
private void btnExportToJson_Click(object sender, EventArgs e)
{
string contents = (DataTableToJSONWithStringBuilder(_dt));
//MessageBox.Show(afd);
System.IO.File.WriteAllText(#"C:\Users\NICK-PC\Desktop\path.json", contents);
Application.Exit();
}
JSon file create coding :
public string DataTableToJSONWithStringBuilder(DataTable table)
{
var jsonString = new StringBuilder();
if (table.Rows.Count > 0)
{
jsonString.Append("[\n");
for (int i = 0; i < table.Rows.Count; i++)
{
jsonString.Append("{\n");
for (int j = 0; j < table.Columns.Count; j++)
{
if (j < table.Columns.Count - 1)
{
jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
table.Rows[i][j].ToString() + "\",\n");
}
else if (j == table.Columns.Count - 1)
{
jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
table.Rows[i][j].ToString() + "\"");
}
}
if (i == table.Rows.Count - 1)
{
jsonString.Append("}");
}
else
{
jsonString.Append("\n},");
jsonString.Append("\n");
}
}
jsonString.Append("\n]");
}
return jsonString.ToString();
}
I used the following code but does not work
public void jsonOps()
{
// Preparing Json object to send to the remote server
jsonLogin li = new jsonLogin();
li.username = "myadmin";
li.password = "log#678*";
string jLoginString = JsonConvert.SerializeObject(li);
// Create HTTP POST request
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.youraddress.com");
httpWebRequest.ContentType = "application/json";
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
string output = "";
// Connecting to the server. Sending request and receiving response
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jLoginString);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
output = streamReader.ReadToEnd();
}
}
// Reading JSON response
JsonTextReader reader = new JsonTextReader(new StringReader(output));
while (reader.Read())
{
if (reader.Value != null)
{
textBox1.Text = reader.Value;
}
else
{
// No value exception block
}
}
I use the following code
private void btnUploadToServer_Click(object sender, EventArgs e)
{
bool connection = NetworkInterface.GetIsNetworkAvailable();
if (connection == true)
{
//MessageBox.Show("Internet Available");
try
{
using (WebClient client = new WebClient())
{
string filePath = #"C:\Users\SAKTHYBAALAN-PC\Desktop\app_sample.json";
var myUri = new Uri(#"http://your_address/path/file.php");
client.UploadFile(myUri, filePath);
client.Credentials = CredentialCache.DefaultCredentials;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
MessageBox.Show("Successfully Uploaded", "Success");
btnExecuteURL.Enabled = true;
}
else
{
MessageBox.Show("There is no internet connection.\n Please make sure that you have an internet connection.", "No Internet");
}
}
I want to resume interrupted resumable upload using Google Drive v3 C# SDK.
The reason why I want this is to create resumable upload in Restful Web API.
There is google drive api instance in this RestAPI, so this is relaying chunk data from client program to google drive.
As you know, client program cannot upload whole file data at one time to Web API, so we need to resume interrupted resumable upload.
So my plan is here.
First, we need to create upload session and receive Session URI.
Second, Create Upload instance every time from returned URI and add chunk data.
Third, repeat 2nd process until EOF.
For this, I made test code, but it does not work at all.
var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open,
System.IO.FileAccess.Read);
var insert = service.Files.Create(new Google.Apis.Drive.v3.Data.File { Name = title }, uploadStream, ContentType);
Uri uploadUri = insert.InitiateSessionAsync().Result;
int chunk_size = ResumableUpload.MinimumChunkSize;
while (uploadStream.Length != uploadStream.Position)
{
byte[] temp = new byte[chunk_size];
uploadStream.Read(temp, 0, temp.Length);
MemoryStream stream = new MemoryStream(temp);
ResumableUpload resume_uploader = ResumableUpload.CreateFromUploadUri(uploadUri, stream);
resume_uploader.ChunkSize = chunk_size;
IUploadProgress ss = resume_uploader.Resume();
Console.WriteLine("Uploaded " + ss.BytesSent.ToString());
}
Frankly, I expected to receive 308 Resume Incomplete Code, but the result is different.
"Invalid request. According to the Content-Range header, the final size of the upload is 262144 byte(s). This does not match the expected size of 1193188 byte(s), which was specified in an earlier request."
This means that I need to create code that resumes interrupted resumable upload using Google Drive C# SDK.
Anybody can help me?
Finally, I solved issue. Exact code is below. Actually, I could not find any source code on Google, so I was so sad. Every developer who wants to solve this issue, use my code please. Hope you are fine. :)
public static async Task<Google.Apis.Drive.v3.Data.File> UploadSync(DriveService driveService, string filepath)
{
string destfilename = Path.GetFileName(filepath);
List<string> parents = new List<string>();
parents.Add("root");
// Prepare the JSON metadata
string json = "{\"name\":\"" + destfilename + "\"";
if (parents.Count > 0)
{
json += ", \"parents\": [";
foreach (string parent in parents)
{
json += "\"" + parent + "\", ";
}
json = json.Remove(json.Length - 2) + "]";
}
json += "}";
Debug.WriteLine(json);
Google.Apis.Drive.v3.Data.File uploadedFile = null;
try
{
System.IO.FileInfo info = new System.IO.FileInfo(filepath);
ulong fileSize = (ulong)info.Length;
var uploadStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
var insert = driveService.Files.Create(new Google.Apis.Drive.v3.Data.File { Name = destfilename, Parents = new List<string> { "root" } }, uploadStream, "application/octet-stream");
Uri uploadUri = insert.InitiateSessionAsync().Result;
int chunk_size = ResumableUpload.MinimumChunkSize;
int bytesSent = 0;
while (uploadStream.Length != uploadStream.Position)
{
byte[] temp = new byte[chunk_size];
int cnt = uploadStream.Read(temp, 0, temp.Length);
if (cnt == 0)
break;
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uploadUri);
httpRequest.Method = "PUT";
httpRequest.Headers["Authorization"] = "Bearer " + ((UserCredential)driveService.HttpClientInitializer).Token.AccessToken;
httpRequest.ContentLength = (long)cnt;
httpRequest.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", bytesSent, bytesSent + cnt - 1, fileSize);
using (System.IO.Stream requestStream = httpRequest.GetRequestStreamAsync().Result)
{
requestStream.Write(temp, 0, cnt);
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
if (httpResponse.StatusCode == HttpStatusCode.OK)
{ }
else if ((int)httpResponse.StatusCode != 308)
break;
bytesSent += cnt;
Console.WriteLine("Uploaded " + bytesSent.ToString());
}
if (bytesSent != uploadStream.Length)
{
return null;
}
// Try to retrieve the file from Google
FilesResource.ListRequest request = driveService.Files.List();
if (parents.Count > 0)
request.Q += "'" + parents[0] + "' in parents and ";
request.Q += "name = '" + destfilename + "'";
FileList result = request.Execute();
if (result.Files.Count > 0)
uploadedFile = result.Files[0];
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return uploadedFile;
}
I am trying to download a file from one FTP server, and then upload it to a different FTP. I only figured out how to upload local files and download XML via FTP so far.
Here is my method to upload local file to FTP:
private void UploadLocalFile(string sourceFileLocation, string targetFileName)
{
try
{
string ftpServerIP = "ftp://testing.com/ContentManagementSystem/"+ Company +"/Prod";
string ftpUserID = Username;
string ftpPassword = Password;
string filename = "ftp://" + ftpServerIP + "/" + targetFileName;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftpReq.Proxy = null;
byte[] b = File.ReadAllBytes(sourceFileLocation);
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
}
catch (WebException ex)
{
String status = ((FtpWebResponse)ex.Response).StatusDescription;
Console.WriteLine(status);
}
}
And here is my method for downloading XML from FTP:
private static XmlDocument DownloadFtpXml(string uri, int retryLimit)
{
var returnDocument = new XmlDocument();
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(Username, Password);
request.UsePassive = true;
request.Proxy = new WebProxy();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
returnDocument.Load(responseStream);
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
}
}
}
return returnDocument;
}
I'm unsure exactly how to do it, but I'm trying to create a method that will download something (content will be a video or image) from one FTP and then turn around and upload what I've just downloaded (that I'll have held in memory) to a different FTP.
Please help!
You were so close! Use a stream to convert your download into a byte array for upload.
I recently made a program to do just this! This will currently copy all files from one FTP directory to another so long as there is not a file in the target directory with the same name. It would be easy to change if you only wanted to copy one file, just use the copyFile, toByteArray and upload functions:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace Copy_From_FTP
{
class Program
{
public static void Main(string[] args)
{
List<FileName> sourceFileList = new List<FileName>();
List<FileName> targetFileList = new List<FileName>();
//string targetURI = ftp://www.target.com
//string targetUser = userName
//string targetPass = passWord
//string sourceURI = ftp://www.source.com
//string sourceUser = userName
//string sourcePass = passWord
getFileLists(sourceURI, sourceUser, sourcePass, sourceFileList, targetURI, targetUser, targetPass, targetFileList);
Console.WriteLine(sourceFileList.Count + " files found!");
CheckLists(sourceFileList, targetFileList);
targetFileList.Sort();
Console.WriteLine(sourceFileList.Count + " unique files on sourceURI"+Environment.NewLine+"Attempting to move them.");
foreach(var file in sourceFileList)
{
try
{
CopyFile(file.fName, sourceURI, sourceUser, sourcePass, targetURI, targetUser, targetPass);
}
catch
{
Console.WriteLine("There was move error with : "+file.fName);
}
}
}
public class FileName : IComparable<FileName>
{
public string fName { get; set; }
public int CompareTo(FileName other)
{
return fName.CompareTo(other.fName);
}
}
public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)
{
for (int i = 0; i < sourceFileList.Count;i++ )
{
if (targetFileList.BinarySearch(sourceFileList[i]) > 0)
{
sourceFileList.RemoveAt(i);
i--;
}
}
}
public static void getFileLists(string sourceURI, string sourceUser, string sourcePass, List<FileName> sourceFileList,string targetURI, string targetUser, string targetPass, List<FileName> targetFileList)
{
string line = "";
/////////Source FileList
FtpWebRequest sourceRequest;
sourceRequest = (FtpWebRequest)WebRequest.Create(sourceURI);
sourceRequest.Credentials = new NetworkCredential(sourceUser, sourcePass);
sourceRequest.Method = WebRequestMethods.Ftp.ListDirectory;
sourceRequest.UseBinary = true;
sourceRequest.KeepAlive = false;
sourceRequest.Timeout = -1;
sourceRequest.UsePassive = true;
FtpWebResponse sourceRespone = (FtpWebResponse)sourceRequest.GetResponse();
//Creates a list(fileList) of the file names
using (Stream responseStream = sourceRespone.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
line = reader.ReadLine();
while (line != null)
{
var fileName = new FileName
{
fName = line
};
sourceFileList.Add(fileName);
line = reader.ReadLine();
}
}
}
/////////////Target FileList
FtpWebRequest targetRequest;
targetRequest = (FtpWebRequest)WebRequest.Create(targetURI);
targetRequest.Credentials = new NetworkCredential(targetUser, targetPass);
targetRequest.Method = WebRequestMethods.Ftp.ListDirectory;
targetRequest.UseBinary = true;
targetRequest.KeepAlive = false;
targetRequest.Timeout = -1;
targetRequest.UsePassive = true;
FtpWebResponse targetResponse = (FtpWebResponse)targetRequest.GetResponse();
//Creates a list(fileList) of the file names
using (Stream responseStream = targetResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
line = reader.ReadLine();
while (line != null)
{
var fileName = new FileName
{
fName = line
};
targetFileList.Add(fileName);
line = reader.ReadLine();
}
}
}
}
public static void CopyFile(string fileName, string sourceURI, string sourceUser, string sourcePass,string targetURI, string targetUser, string targetPass )
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceURI + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(sourceUser, sourcePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Upload(fileName, ToByteArray(responseStream),targetURI,targetUser, targetPass);
responseStream.Close();
}
catch
{
Console.WriteLine("There was an error with :" + fileName);
}
}
public static Byte[] ToByteArray(Stream stream)
{
MemoryStream ms = new MemoryStream();
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
{
ms.Write(chunk, 0, bytesRead);
}
return ms.ToArray();
}
public static bool Upload(string FileName, byte[] Image, string targetURI,string targetUser, string targetPass)
{
try
{
FtpWebRequest clsRequest = (FtpWebRequest)WebRequest.Create(targetURI+FileName);
clsRequest.Credentials = new NetworkCredential(targetUser, targetPass);
clsRequest.Method = WebRequestMethods.Ftp.UploadFile;
Stream clsStream = clsRequest.GetRequestStream();
clsStream.Write(Image, 0, Image.Length);
clsStream.Close();
clsStream.Dispose();
return true;
}
catch
{
return false;
}
}
}
}
You may run into issues if you are using things that have special encoding, like text documents. That can be changed by the way the upload function is used. If you're doing text files, use:
System.Text.Encoding.UTF8.GetBytes(responseStream)
instead of
ToByteArray(responseStream)
You could do a simple extension check of your file before executing the upload.
I am getting files from ftp folder like this.
request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://ipaddress/foldername"));
request.UseBinary = true;
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.UseBinary = true;
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
string[] results = result.ToString().Split('\n');
foreach (string filename in results)
{
connetionString = "Data Source=testservername;Initial Catalog=testdb;User ID=sa;Password=sa";
connection = new SqlConnection(connetionString);
FtpWebRequest request1 = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://servername/" + filename));
request1.Method = WebRequestMethods.Ftp.DownloadFile;
request1.UseBinary = true;
request1.Credentials = new NetworkCredential("username", "password");
responses = (FtpWebResponse)request1.GetResponse();
StreamReader reader1 = new StreamReader(responses.GetResponseStream());
string xml = reader1.ReadToEnd();
ds.ReadXml(new XmlTextReader(new StringReader(xml)));
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[1].Rows.Count - 1 ; i++)
{
sql = "insert into Details values('" + ds.Tables[1].Rows[i].ItemArray[0]
+ "')";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
FtpWebRequest requestDelete = (FtpWebRequest)WebRequest.Create("ftp://sername/" + filename);
requestDelete.Method = WebRequestMethods.Ftp.DeleteFile;
requestDelete.UseBinary = true;
requestDelete.Credentials = new NetworkCredential("username", "password");
responseDelete = (FtpWebResponse)requestDelete.GetResponse();
try
{
string res = responseDelete.StatusDescription;
if (res == "250 Delete operation successful.")
{
MessageBox.Show("Done......");
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
responseDelete.Close();
connection.Close();
responses.Close();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
Hi need to get files from ftp folder and read that xml files one by one and save it as records in my Databse after that need to delete that file ftp folder.
if for testing i placed two files in ftp folder first files reading successfully .but getting error for reading second file like "Object Reference is not set instance of object "in the below line.
ds.ReadXml(new XmlTextReader(new StringReader(xml)));
please tell me any thing wrong in my code.i am sending ftp request multiple times it is good or suggest me by seeing above lines of code how to do that?
I'm trying to retrieve a list of files from an FTP server, but I'm getting some weird non-ASCII responses.
Here is the code that I am using:
public string[] getFileList(string mask)
{
if(!logined)
{
login();
}
Socket cSocket = createDataSocket();
this.getSslDataStream(cSocket);
sendCommand("PASV");
sendCommand("LIST " + "*"+mask);
stream2.AuthenticateAsClient(remoteHost,
null,
System.Security.Authentication.SslProtocols.Ssl3 |
System.Security.Authentication.SslProtocols.Tls,
true);
if(!(retValue == 150 || retValue == 125))
{
throw new IOException(reply.Substring(4));
}
StringBuilder mes = new StringBuilder();
while(true)
{
int bytes = cSocket.Receive(buffer, buffer.Length, 0);
mes.Append(ASCII.GetString(buffer, 0, bytes));
if(bytes < buffer.Length)
{
break;
}
}
string[] seperator = {"\r\n"};
string[] mess = mes.ToString().Split(seperator, StringSplitOptions.RemoveEmptyEntries);
cSocket.Close();
readReply();
if(retValue != 226)
{
throw new IOException(reply.Substring(4));
}
return mess;
}
The response I get from the FTP server is this:
WRITE:PASV
READ:227 Entering Passive Mode (10,0,2,24,5,119)`
WRITE:LIST *.dat
READ:150 Opening ASCII mode data connection for /bin/ls.
READ:226 Transfer complete.
It stops there. The string array that it returns contains one index with some non-ascii characters. Looks like a bunch of garbage. Perhaps my ASCII.GetString part is wrong? I'm not quite sure.
Thanks in advance.
I wrote a pretty easy to use wrapper library for all the FtpWebRequest stuff. If you care to check it out, it's here https://gist.github.com/1242616
I use it in a lot of production environments and it hasn't failed me yet.
For what it's worth, the System.Net namespace has the FtpWebRequest and FtpWebResponse classes beginning in .Net 2.0.
Here's some code I've used that writes the server's files to a local file:
...
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(address);
ftpRequest.Credentials = new NetworkCredential(username, password);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.KeepAlive = false;
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
sr = new StreamReader(ftpResponse.GetResponseStream());
sw = new StreamWriter(new FileStream(fileName, FileMode.Create));
sw.WriteLine(sr.ReadToEnd());
sw.Close();
ftpResponse.Close();
sr.Close();
...
public Socket BuildDataConn(Socket FirstSocket)
{
string ret = "";
string RemoteIP = "";
int RemotePort = 0;
SendCommand("PASV");
int id = 0;
id = strMsg.LastIndexOf(')');
if (id != 0)
{
string tmp = strMsg.Substring(strMsg.LastIndexOf('(') + 1, id - strMsg.LastIndexOf('(') - 1);
string[] bByte = tmp.Split(',');
RemotePort = int.Parse(bByte[4]) * 256 + Byte.Parse(bByte[5]);
RemoteIP = bByte[0]+"." + bByte[1] + "." + bByte[2] + "." + bByte[3];
}
Socket NewConn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint RemoteIPPort = new IPEndPoint(IPAddress.Parse(RemoteIP), RemotePort);
try
{
NewConn.Connect(RemoteIPPort);
}
catch
{
throw new IOException("unable to Connect !");
}
return NewConn;
}
Instead of using cSocket to receive response data,you need to get a second socket and then use the socket to receive response data. the second socket will response for sending back information. And make sure you had change your FTP working directory before you sendcommand LIST.
public List<string> GetFileNames()
{
if (!bConnected)
{
Open();
}
List<string> retObj = new List<string>();
Socket dataSock = BuildDataConn(mySocket);
SendCommand("NLST");
string dataSockMsg = "";
buffer = new byte[BLOCK_SIZE];
while (true)
{
int iBytes = dataSock.Receive(buffer, buffer.Length, 0);
dataSockMsg += System.Text.Encoding.ASCII.GetString(buffer, 0, iBytes);
if (iBytes < buffer.Length)
{
break;
}
}
string[] message = dataSockMsg.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
dataSock.Close();
foreach (string obj in message)
{
retObj.Add(obj);
}
return retObj;
}