Using the following program I’m trying to insert all the filenames listed in a folder on ftp server into a SQL table.
While Writing to table I’m getting an error
c# cannot access a disposed object. object name
‘system.net.sockets.networkstream’
reader.ReadToEnd() Writing the whole stream where I want one by one filename.
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main()
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myftpaddress.com/0708/");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("vish10", "MyPasswd");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
SqlConnection sqlConnection1 = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DMSTG;Data Source=.");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = @"Insert into FTPfileList0708Folder
values('" + reader.ReadToEnd().ToString() + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
}
You’ve already read the complete response here:
Once you’ve read it, you can’t read it again.
Just change to
… and then add appropriate
usingstatements to handle resources properly:You should have similar
usingstatements for all of your SQL-related resources.That solves the immediate problem – but it’s not clear what that has to do with the specific business of reading filenames. That will depend on what format the filenames are in within the text. From what I remember, FTP is actually very poorly specified when it comes to this sort of thing.
I would recommend two significant changes: