简体   繁体   中英

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

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
});

In your case, you know you are not on the UI thread, but if you have a function that could be called either from the UI thread or a worker thread, you need to check InvokeRequired :

string line = reader.ReadLine();
if ( listView1.InvokeRequired ) {
    listView1.Invoke((MethodInvoker)delegate {
        listView1.Items.Add(line); // runs on UI thread
    });
}
else {
    // we're already on UI thread - work on ListView1 directly
    listView1.Items.Add(line);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM