Very simple question but this has been annoying me for a few days. I have tried quite a few different things to get this working but its starting to piss me off.
So basically I am trying to get a simple WPF app to run through a folder, copy some files and update a textbox as it goes. I have setup a new thread for the copying method so the UI thread isn't hung up and I am using dispatcher.invoke to send back to the UI thread for updating. However because my file copying method is in a different class to the textbox it doesn't update the textbox. I have tried passing the textbox to the copying method as I read this would be a solution but this doesn't appear to work. Or I misunderstood what was being suggested (equally as likely).
You can find my code below. BEWARE: I read a few chapters of a C# book and then just jumped in (as I always do) so my code is likely to be messy.
namespace DeleteTempFiles
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
// Copy stuff. To allow 'fileBox' to be parsed at thread Start. There must be a nicer way to do this.
public void copyStuff()
{
try
{
DeleteStuff accessDeleteStuff = new DeleteStuff();
accessDeleteStuff.GetAllFiles(fileBox);
}
catch (Exception goneWrong)
{
MessageBox.Show(goneWrong.Message);
}
}
// GUI Button click starts thread
public void displayFiles_Click(object sender, RoutedEventArgs e)
{
try
{
Window1 threadOne = new Window1();
Thread deletingThread = new Thread(threadOne.copyStuff);
deletingThread.SetApartmentState(ApartmentState.STA);
deletingThread.Start();
}
catch (Exception goneWrong)
{
MessageBox.Show(goneWrong.Message);
}
}
}
// Worker Class
public class DeleteStuff
{
// Method for looping through directory and copying x amount of files to another directory.
public void GetAllFiles(TextBox fileBox)
{
try
{
int count = 1;
string startDir = "D:/Pictures/";
string finishDir = "D:/Copies/";
string[] fileEntries = Directory.GetFiles(startDir);
foreach (string fileName in fileEntries)
{
// Only copy 10 files
if (count <= 10)
{
string outcome = fileName.Replace(startDir, finishDir);
File.Delete(outcome);
File.Copy(fileName, outcome);
// Try and update UI fileBox with copy file progress.
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
{
fileBox.Text = fileBox.Text += "File: " + fileName + " Successfully Copied!" + '\n';
}
));
count++;
}
}
}
catch (Exception goneWrong)
{
MessageBox.Show(goneWrong.Message);
}
}
}
}
Any help on fixing this to work would be much appreciated.
Thanks for your time.
P.S - The Names relate to what I plan to do with the program if I can get it working. So thats why they don't make any sense ;)