SHoCK SHoCK - 1 month ago 15
C# Question

Listing Files From FTP in ListView using BackGround Worker in C#

I am working on a application which will check the ftp server and list all files of directory, that work perfectly without BACKGROUND WORKER but when i use Background worker, lot of problem occurs.
The first problem was that i cannot access ListView from BackGround worker, i used another method (store the list in Array and then Update on BackGround Worker Process Complete) but it did'nt worked.
Then i used another form which was Hidden and doing same function but the program still stuck at listing FTP files.
Actually, i just want to list files of this directory(ftp://blah/subdir/[files are here]) to ListView1. How it is Possible without Freezing UI? i tried to use Background worker but it did'nt worked, how can use it to work?
Here is Code

function

public string[] ListDirectory()
{
string hostdir = textBoxX2.Text + textBoxX3.Text;
var request = createRequest(hostdir,WebRequestMethods.Ftp.ListDirectory);
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, true))
{
while (!reader.EndOfStream)
{
listView1.Items.Add(reader.ReadLine());
}
}
}
}
List<string> l = new List<string>();
return l.ToArray();
}
private FtpWebRequest createRequest(string uri, string method)
{
var r = (FtpWebRequest)WebRequest.Create(uri);
r.Credentials = new NetworkCredential(textBoxX4.Text, textBoxX5.Text);
r.Method = method;
return r;
}


The Code above Works But freezes UI, and when i use background worker, some of functions not working like, cannot access ListView1 from Object it was created on or Something Similar.

Any Help Appreciated...
Thanks

Answer

You could try this approach - the Invoke runs the action on the appropriate thread:

string line = reader.ReadLine();
listView1.Invoke((MethodInvoker)delegate {
    listView1.Items.Add(line); // runs on UI thread
});