How to debug an endless running variable? - c#

I tried to write an autoupdater for a program from me.
I already got rid of a stackOverflow and such but now my Program seems to run endless when he comes to a variable. And do nothing.
I tried to get info with cw and check where it is hanging but i get nothing and can not find it.
My main
{
updater = new Updater(this);
updater.DoUpdate();
}
public string ApplicationName {
get { return "MyProgram"; }
}
public string ApplicationID {
get { return "MyProgramID"; }
}
public Assembly ApplicationAssembly {
get { return System.Reflection.Assembly.GetExecutingAssembly(); }
}
public Icon ApplicationIcon {
get { return this.Icon; }
}
public Uri UpdateXmlLocation {
get { return new Uri("UrlToXml"); }
}
public Form Context {
get { return this; }
}
in my XML class
public class UpdateXml
{
private Version version;
public Uri uri;
private string fileName;
private string md5;
private string description;
private string launchArgs;
internal Version Version {
get { return this.Version; }
}
internal Uri Uri {
get { return this.Uri; }
}
internal string FileName {
get { return this.fileName; }
}
internal string MD5 {
get { return this.md5; }
}
internal string Description {
get { return this.description; }
}
internal string LaunchArgs {
get { return this.launchArgs; }
}
after a while (code running fine it come to the part that crash)
private void DwnloadUpdate(UpdateXml update)
{
updateDownloadForm form = new updateDownloadForm(update.Uri, this.applicationInfo.ApplicationIcon);
after this code I expect that my dl windows open and the dl starts and the program get update
My Updater class
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace updater
{
public class Updater
{
private Iupdater applicationInfo;
private BackgroundWorker bgWorker;
public Updater(Iupdater applicationInfo)
{
this.applicationInfo = applicationInfo;
this.bgWorker = new BackgroundWorker();
this.bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
this.bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
}
public void DoUpdate()
{
if (!this.bgWorker.IsBusy)
this.bgWorker.RunWorkerAsync(this.applicationInfo);
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
Iupdater application = (Iupdater)e.Argument;
if (!UpdateXml.ExistOnServer(application.UpdateXmlLocation))
{
e.Cancel = true;
}
else
{
UpdateXml ux = UpdateXml.Parse(application.UpdateXmlLocation, application.ApplicationID);
if (ux == null)
{
e.Cancel = true;
}
else
{
e.Result = ux;
}
}
}
void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(!e.Cancelled)
{
UpdateXml update = (UpdateXml)e.Result;
if(update == null)
{
Console.WriteLine("Update NULL");
}
Console.WriteLine("test3.1");
Console.WriteLine(this.applicationInfo.ApplicationAssembly.GetName().Version);
if(this.applicationInfo.ApplicationAssembly.GetName().Version != null)
{
Console.WriteLine("YES!");
} else
{
Console.WriteLine("NO!");
}
Console.WriteLine("test3.2");
if (update != null && update.IsNewerThan(this.applicationInfo.ApplicationAssembly.GetName().Version))
{
Console.WriteLine("test4");
if (new updateInformation(applicationInfo, update).ShowDialog(this.applicationInfo.Context) == DialogResult.Yes)
this.DwnloadUpdate(update);
}
}
}
private void DwnloadUpdate(UpdateXml update)
{
Console.WriteLine(update.Uri);
if(update.Uri == null)
Console.WriteLine("null");
updateDownloadForm form = new updateDownloadForm(update.Uri, this.applicationInfo.ApplicationIcon);
Console.WriteLine("ich bin hier drinnen");
DialogResult result = form.ShowDialog(this.applicationInfo.Context);
if(result == DialogResult.OK)
{
string currentPath = this.applicationInfo.ApplicationAssembly.Location;
string newPath = Path.GetDirectoryName(currentPath) + "\\" + update.FileName;
UpdateApplication(form.TempFilePath, currentPath, newPath, update.LaunchArgs);
Application.Exit();
}
else if(result == DialogResult.Abort)
{
MessageBox.Show("The update download was cancelled. \nThis programm has not been modified.", "Update Download Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("There was a Problem downloading the Updat. \nThis programm has not been modified.", "Update Download Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpdateApplication(string tempFilePath, string currentPath, string newPath, string launchArgs)
{
string argument = "/C Choice /C Y /N /D Y /T 4 & Del /F /Q \"{0}\" & Choice /C Y /N /D Y /T 2 & Move /Y \"{1}\" \"{2}\" & Start \"\" /D \"{3}\" \"{4}\"{5}";
ProcessStartInfo info = new ProcessStartInfo();
info.Arguments = string.Format(argument, currentPath, tempFilePath, newPath, Path.GetDirectoryName(newPath), Path.GetFileName(newPath), launchArgs);
info.CreateNoWindow = true;
info.FileName = "cmd.exe";
Process.Start(info);
}
}
}
my XML Updater class
using System;
using System.Net;
using System.Xml;
namespace updater
{
public class UpdateXml
{
private Version version;
public Uri uri;
private string fileName;
private string md5;
private string description;
private string launchArgs;
internal Version Version {
get { return this.Version; }
}
internal Uri Uri {
get { return this.Uri; }
}
internal string FileName {
get { return this.fileName; }
}
internal string MD5 {
get { return this.md5; }
}
internal string Description {
get { return this.description; }
}
internal string LaunchArgs {
get { return this.launchArgs; }
}
internal UpdateXml(Version version, Uri uri, string fileName, string md5, string description, string launchArgs)
{
Console.WriteLine("run in1");
this.version = version;
this.uri = uri;
this.fileName = fileName;
this.md5 = md5;
this.description = description;
this.launchArgs = launchArgs;
Console.WriteLine("run out 1");
}
internal bool IsNewerThan(Version version)
{
Console.WriteLine("run in 2");
return this.version > version;
}
internal static bool ExistOnServer(Uri location)
{
try
{
Console.WriteLine("run in 3");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(location.AbsoluteUri);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Console.WriteLine("run out 3");
return res.StatusCode == HttpStatusCode.OK;
}
catch { return false; }
}
internal static UpdateXml Parse(Uri location, string appID)
{
Console.WriteLine("run in 4");
Version version = null;
string url = "", fileName = "", md5 = "", description = "", launchArgs = "";
try
{
XmlDocument doc = new XmlDocument();
doc.Load(location.AbsoluteUri);
XmlNode node = doc.DocumentElement.SelectSingleNode("//update");
if(node == null)
{
return null;
}
version = Version.Parse(node["version"].InnerText);
url = node["url"].InnerText;
fileName = node["fileName"].InnerText;
md5 = node["md5"].InnerText;
description = node["description"].InnerText;
launchArgs = node["launchArgs"].InnerText;
Console.WriteLine("run out 4");
return new UpdateXml(version, new Uri(url), fileName, md5, description, launchArgs);
}
catch
{
return null;
}
}
}
}
My interfaces
using System;
using System.Reflection;
using System.Drawing;
using System.Windows.Forms;
namespace updater
{
public interface Iupdater
{
string ApplicationName { get; }
string ApplicationID { get; }
Assembly ApplicationAssembly { get; }
Icon ApplicationIcon { get; }
Uri UpdateXmlLocation { get; }
Form Context { get; }
}
}
my update start form where it seems to go into a loop
using System;
using updater;
using System.Windows.Forms;
namespace updater
{
internal partial class updateInformation : Form
{
private Iupdater applicationInfo;
private UpdateXml updateInfo;
private UpdateInoForm updateInoForm;
public updateInformation(Iupdater applicationInfo, UpdateXml updateInfo)
{
InitializeComponent();
this.applicationInfo = applicationInfo;
this.updateInfo = updateInfo;
this.Text = this.applicationInfo.ApplicationName + " - Update in Process";
if (this.applicationInfo.ApplicationIcon != null)
this.Icon = this.applicationInfo.ApplicationIcon;
//this.lblNewVersion.Text = String.Format("New Version: {0}", this.updateInfo.Version.ToString());
Timer wait = new Timer();
wait.Interval = 5000;
wait.Tick += new EventHandler(wait_Tick);
wait.Start();
}
void wait_Tick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Yes;
}
private void Details_Click(object sender, EventArgs e)
{
if (this.updateInfo == null)
this.updateInoForm = new UpdateInoForm(this.applicationInfo, this.updateInfo);
this.updateInoForm.ShowDialog(this);
}
}
}

You need to return the field values, instead of the properties returning the property value. Do not write properties like this:
/// THIS PROPERTY TRIES TO RETURN ITSELF!!
internal Version Version {
get {
return this.Version; // you wanted to return 'this.version'
}
}
You can use auto-properties like this:
// No more private fields
public class UpdateXml
{
public Version Version { get; set; }
public string FileName { get; } // Only expose a getter, can be set in the ctor
public Uri Uri { get; set; }
// add more properties here...
public UpdateXml(string filename)
{
FileName = filename;
}
}
Or learn to use a convention seen allot in C#. Prefix the private variable names:
public class UpdateXml
{
private Version _version;
private string _fileName;
private Uri _uri;
public Version Version => _version;
public string FileName => _filename;
public Uri Uri {
get => _uri;
set => _uri = value;
}
// add more properties here...
// use the ctor to set some field values
public UpdateXml(string filename)
{
_filename = filename;
}
// fields allow setting values later on
public void SetLatestVersion(Version v)
{
if (_version == null || v > _version)
_version = v;
}
}
All in all, take care when writing code. Case does matter ;-)

Related

Object is null when I want to delete its content

I'm doing some WPF project where I want to make a method, which deletes element from ObservableCollection when I click on it. But for some reason is not doing right. I check with debugger and when it comes to the statement where I call method for the removing element, it shows that my object (on which I call all methods) is empty or. null.
I know it's dumb question and for sure very dumb mistake, which I overlooked but I can't find the solution how to fix it.
Code:
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace facebook {
/// <summary>
/// Interaction logic for prikazObjave.xaml
/// </summary>
public partial class prikazObjave : UserControl {
Oseba oseba = new Oseba();
public prikazObjave() {
InitializeComponent();
}
public prikazObjave(Oseba os) {
InitializeComponent();
oseba = os;
}
private void item_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
var TextBlockName = ((TextBlock)sender).Name;
string newValue = Interaction.InputBox("Vnesi novo vrednost", "New value", "", 0, 0);
if (newValue != "" && newValue != null) {
((TextBlock)sender).Text = newValue;
}
}
private void delete_post_event(object sender, MouseButtonEventArgs e) {
var temp = (StackPanel)sender;
Objava objava = (Objava)(temp.DataContext);
if(oseba.posts.Count > 1) { //<---here, oseba is null
try {
oseba.izbrisiObjavo(oseba, objava);
MessageBox.Show("Objava uspešno izbrisana");
}
catch (Exception ex) {
Console.WriteLine("Napaka pri brisanju objave\n\n" + ex.Message + "\n" + ex.StackTrace);
}
}
else {
Console.WriteLine("Seznam objav je prazen");
return;
}
}
private void dodajKomentarBtn_Click(object sender, RoutedEventArgs e) {
string vsebina = Interaction.InputBox("Vnesi komentar", "Komentiraj", "", 0, 0);
if (vsebina != "" && vsebina != null) {
oseba.dodajKomentar(vsebina);
}
}
}
}
And this is the class method for removing the element from the Collection:
public void izbrisiObjavo(Oseba oseba, Objava objava) {
if(objava != null) {
//posts.Remove(objava);
try {
//posts.Remove(posts.Where(i => i.Vsebina == objava.Vsebina).Single());
Objava temp = objava;
oseba.posts.Remove(temp);
}
catch(Exception e) {
Console.WriteLine("Napaka pri brisanju objave (Oseba)\n\n" + e.Message + "\n" + e.StackTrace);
}
}
else {
Console.WriteLine("objava je null\n");
return;
}
}
Oseba class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Windows.Forms;
namespace facebook {
[Serializable()]
public class Oseba : INotifyPropertyChanged {
private string ime;
private string priimek;
private int starost;
private string spol;
private string oMeni;
private string zaposlitev;
private string profilnaSlika;
private string naslovnaSlika;
ObservableCollection<String> solanje = new ObservableCollection<string>(); //vse vrste šolanja
ObservableCollection<Prijatelj> friends = new ObservableCollection<Prijatelj>(); //seznam prijateljev
ObservableCollection<Objava> posts = new ObservableCollection<Objava>(); //seznam objav
ObservableCollection<String> pocutje = new ObservableCollection<string>();
public Oseba() { }
public Oseba(string ime, string priimek, int starost, string spol, string oMeni, string zaposlitev) {
this.ime = ime;
this.priimek = priimek;
this.starost = starost;
this.spol = spol;
this.oMeni = oMeni;
this.zaposlitev = zaposlitev;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName) {
if(PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public void dodajPrijatelja(Prijatelj prijatelj) {
friends.Add(prijatelj);
}
public void dodajSolo(string sola) {
solanje.Add(sola);
}
public void dodajObjavo(string vsebina, string zasebnost, ObservableCollection<String> prijatelji, string datoteka, string kraj, string pocutje) {
posts.Add(new Objava(vsebina, zasebnost, prijatelji, datoteka, kraj, pocutje));
}
public void dodajPocutje(string path) {
pocutje.Add(path);
}
public void dodajKomentar(string vsebina) {
if(vsebina != null) {
try {
//posts[0].ko
}
catch (Exception e) {
MessageBox.Show("Napaka pri dodajanju komentarja!\n\n" + e.Message + "\n" + e.StackTrace);
}
}
else {
MessageBox.Show("Vnesite komentar!");
return;
}
}
public void izbrisiObjavo(Oseba oseba, Objava objava) {
if(objava != null) {
//posts.Remove(objava);
try {
//posts.Remove(posts.Where(i => i.Vsebina == objava.Vsebina).Single());
Objava temp = objava;
oseba.posts.Remove(temp);
}
catch(Exception e) {
Console.WriteLine("Napaka pri brisanju objave (Oseba)\n\n" + e.Message + "\n" + e.StackTrace);
}
}
else {
Console.WriteLine("objava je null\n");
return;
}
}
public void serialize(Oseba os) {
string dataFile = (#"C:\Users\Admin\Desktop\uv\data.xml");
profilnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_profile_pic.jpg";
naslovnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_timeline_pic.jpg";
try {
XmlSerializer mySerializer = new XmlSerializer(typeof(Oseba));
StreamWriter myWritter = new StreamWriter(dataFile);
mySerializer.Serialize(myWritter, os);
myWritter.Close();
}
catch(Exception ex) {
Console.WriteLine("Napaka pri serializaciji(metoda Serialize - razred Oseba)\n\n" + ex.Message + "\n" + ex.StackTrace);
}
}
public Oseba deserialize(string path = #"C:\Users\Admin\Desktop\uv\data.xml") {
Oseba os = new Oseba();
string dataFile = path;
try {
using (var sr = new StreamReader(dataFile)) {
var deserializer = new XmlSerializer(typeof(Oseba));
os = (Oseba)deserializer.Deserialize(sr);
}
}
catch (Exception ex) {
Console.WriteLine("Napaka pri deserializaciji\n\n" + ex.Message + "\n" + ex.StackTrace);
}
return os;
}
public void shrani() {
string dataFile = (#"C:\Users\Admin\Desktop\data.xml");
profilnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_profile_pic.jpg";
naslovnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_timeline_pic.jpg";
using (var stream = new FileStream(dataFile, FileMode.Create)) {
var XML = new XmlSerializer(typeof(Oseba));
XML.Serialize(stream, this);
}
}
public Oseba nalozi() {
Oseba os = new Oseba();
string dataFile = (#"C:\Users\Admin\Desktop\data.xml");
try {
using (var sr = new StreamReader(dataFile)) {
var deserializer = new XmlSerializer(typeof(Oseba));
os = (Oseba)deserializer.Deserialize(sr);
}
}
catch (Exception ex) {
var msg = ex.Message;
}
return os;
}
public void odstraniPrijatelja(int index) {
friends.RemoveAt(index);
}
/*
public void sortAsc() {
ObservableCollection<string> prijatelji = new ObservableCollection<string>(friends.OrderBy(i => i));
friends = prijatelji;
}
public void sortDecs() {
ObservableCollection<string> prijatelji = new ObservableCollection<string>(friends.OrderByDescending(i => i));
friends = prijatelji;
}
*/
public string Ime {
get { return ime; }
set {
ime = value;
OnPropertyChanged("Ime");
}
}
public string Priimek {
get { return priimek; }
set {
priimek = value;
OnPropertyChanged("Priimek");
}
}
public int Starost {
get { return starost; }
set {
starost = value;
OnPropertyChanged("Starost");
}
}
public string Spol {
get { return spol; }
set {
spol = value;
OnPropertyChanged("Spol");
}
}
public string OMeni {
get { return oMeni; }
set {
oMeni = value;
OnPropertyChanged("OMeni");
}
}
public string Zaposlitev {
get { return zaposlitev; }
set {
zaposlitev = value;
OnPropertyChanged("Zaposlitev");
}
}
public string ProfilnaSlika {
get { return profilnaSlika; }
set {
profilnaSlika = value;
OnPropertyChanged("ProfilnaSlika");
}
}
public string NaslovnaSlika {
get { return naslovnaSlika; }
set {
naslovnaSlika = value;
OnPropertyChanged("NaslovnaSlika");
}
}
public ObservableCollection<Prijatelj> Friends {
get { return friends; }
set { friends = value;
OnPropertyChanged("Friends");
}
}
public ObservableCollection<String> Solanje {
get { return solanje; }
set {
solanje = value;
OnPropertyChanged("Solanje");
}
}
public ObservableCollection<Objava> Posts {
get { return posts; }
set {
posts = value;
OnPropertyChanged("Posts");
}
}
[XmlIgnore]
public ObservableCollection<String> Pocutje {
get { return pocutje; }
set {
pocutje = value;
OnPropertyChanged("Pocutje");
}
}
}
}
I feel like the silly thing that could possibly lead to this is creating a new prikazObjave (which should be Capitalized class name) as:
var po = new prikazObjave(null);
This would lead to the internal oseba to be null, unless you're explicitly setting po.oseba = null; somewhere.
I debugged my program in chunks and I found that every global variable in userControl named PrikazObjave is null after constructor call is finish.

Saving keeps overwriting itself C#

I am making an application which will save and load products. These products have three properties of a product name, customer name and firmware location. However, when I try to save them, it will only save one and keeps overwriting with the most recent product saved. The following is my code for the product class:
public class Product
{
//private product data
private string productName;
public string getProductName()
{
return this.productName;
}
public void setProductName (string inProductName)
{
this.productName = inProductName;
}
private string customerName;
public string getCustomerName()
{
return this.customerName;
}
public void setCustomerName (string inCustomerName)
{
this.customerName = inCustomerName;
}
private string firmwareLocation;
public string getFirmwareLocation()
{
return this.firmwareLocation;
}
public void setFirmwareLocation (string inFirmwareLocation)
{
this.firmwareLocation = inFirmwareLocation;
}
//constructor
public Product (string inProductName, string inCustomerName, string inFirmwareLocation)
{
productName = inProductName;
customerName = inCustomerName;
firmwareLocation = inFirmwareLocation;
}
//save method
public void Save (System.IO.TextWriter textOut)
{
textOut.WriteLine(productName);
textOut.WriteLine(customerName);
textOut.WriteLine(firmwareLocation);
}
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
At the end is my save methods.
Here is the code for when the user presses the add product button:
private void Add_Click(object sender, RoutedEventArgs e)
{
//get input from user
string inputCustomerName = customerNameTextBox.Text;
string inputProductName = productNameTextBox.Text;
string inputFirmwareLocation = firmwareTextBox.Text;
try
{
Product newProduct = new Product(inputProductName, inputCustomerName, inputFirmwareLocation);
newProduct.Save("products.txt");
MessageBox.Show("Product added");
}
catch
{
MessageBox.Show("Product could not be added");
}
}
You are not appending the text to your file, thats why it keeps overwriting the last entry over and over again.
Try to change your save method to:
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename, true);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
Notice the "true" as the second parameter in the StreamWriter constructor. This tells the StreamWriter to append the new line.

C# Exception not being handled

Currently working on a small project, which includes a Registry form, where users can Sign up log in. I have error providers which tell the user if the information they have entered is incorrect or not. For some reason the exceptions are no longer being handled, even though they were a while back.
Here is the code for when the user presses the 'Register Button'
private void btnRegister_Click(object sender, EventArgs e)
{
//Try - Catch Statements
//Try to set the forename
try
{
player1.Forename = txtForename.Text;
player2.Forename = txtForename.Text;
errForename.Icon = Properties.Resources.Correct;
errForename.SetError(txtForename, "OK");
}
catch (NewException exc)
{
errForename.SetError(txtForename, exc.MessageM);
}
It then does this for other details, e.g surname, username.
Here is the User class getters and setters
public string Forename
{
get
{
return forename;
}
set
{
bool okChar = OnlyChars(value, "Forename");
if (okChar == true)
forename = value;
else
{
throw new NewException(errorMessage);
forename = null;
}
}
}
And finally here is the NewException class that I wrote
namespace Colludia
{
class NewException : Exception
{
private string messageM;
public NewException() : base()
{
}
public NewException(string message) : base(message)
{
messageM = message;
}
public string MessageM
{
get { return messageM; }
set { messageM = value; }
}
}
}
This is working code for you.
I think its issue of namespace
using System;
class Player
{
string forename = "";
string errorMessage = "";
public string Forename
{
get
{
return forename;
}
set
{
bool okChar = OnlyChars(value, "Forename");
if (okChar == true)
forename = value;
else
{
throw new NewException(errorMessage);
}
}
}
private bool OnlyChars(string value, string p)
{
if (value == p)
return true;
else
{
errorMessage = "Err";
return false;
}
}
}
class NewException : Exception
{
private string messageM;
public NewException()
: base()
{
}
public NewException(string message)
: base(message)
{
messageM = message;
}
public string MessageM
{
get { return messageM; }
set { messageM = value; }
}
}
class Program
{
static void Main(string[] args)
{
try
{
var player1 = new Player();
var player2 = new Player();
player1.Forename = "asdfg";
player2.Forename = "qwerty";
}
catch (NewException exc)
{
bool error = true;
}
}
}

append text to textbox from another class using background worker

sorry for bugging you guys with such a small problem, but I cannot find a solution. I have created one class for getting attachments from exchange server and Form for adding server configuration and textbox which I attend to use for the log output. I have added backgroundWorker to create separate thread and when class gets right attachment and collect info for the output, it redirects to backgroundWorker DoWork method. The problem is that UI of the textbox is simply doesn't want to append text
Class for downloading attachment looks like:
namespace DownloadAttachmentExchange
{
class ExchangeDwnClass
{
private string path_ = "";
private string filterSender_ = "";
private string subject_ = "";
private string id_ = "";
private string username_ = "";
private string password_ = "";
private string exchange_ = "";
private string filterExcel_ = "";
private string filterCSV_ = "";
private string attachmentName_ = "";
private int emailFetch_ = 0;
private DateTime current_;
ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
public string Path
{
get { return path_; }
set { path_ = value; }
}
public string FilterSender
{
get { return filterSender_; }
set { filterSender_ = value; }
}
public string Subject
{
get { return subject_; }
set { subject_ = value; }
}
public string ID
{
get { return id_; }
set { id_ = value; }
}
public string Username
{
get { return username_; }
set { username_ = value; }
}
public string Password
{
get { return password_; }
set { password_ = value; }
}
public string Exchange
{
get { return exchange_; }
set { exchange_ = value; }
}
public string FilterExcel
{
get { return filterExcel_; }
set { filterExcel_ = value; }
}
public string FilterCsv
{
get { return filterCSV_; }
set { filterCSV_ = value; }
}
public string AttachementName
{
get { return attachmentName_; }
set { attachmentName_ = value; }
}
public int EmailFetch
{
get { return emailFetch_; }
set { emailFetch_ = value; }
}
public DateTime CurrentDate
{
get { return current_; }
set { current_ = value; }
}
public void GetAttachments()
{
try
{
serv.Credentials = new WebCredentials(Username, Password);
serv.AutodiscoverUrl(Exchange);
ItemView view = new ItemView(10);
FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));
if (result != null && result.Items != null && result.Items.Count > 0)
{
foreach (Item item in result.Items)
{
EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
if (msg.Sender.ToString().Contains(FilterSender) && msg.From.ToString().Contains(FilterSender))
{
foreach (Attachment att in msg.Attachments)
{
if (att is FileAttachment)
{
FileAttachment file = att as FileAttachment;
if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
{
Form1 form = new Form1();
file.Load(Path +"\\"+ file.Name);
AttachementName = file.Name.ToString();
Subject = item.Subject.ToString();
ID = item.Id.ToString();
CurrentDate = DateTime.Now;
form.date = CurrentDate.ToString();
form.subject = Subject;
form.attachment = AttachementName;
form.backgroundWorker1.RunWorkerAsync();
Thread.Sleep(60000);
}
}
}
}
//item.Delete(DeleteMode.HardDelete);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public void StopDownloadingAttachment()
{
}
}
}
Form looks like this:
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string date = "";
public string attachment = "";
public string subject = "";
public Form1()
{
InitializeComponent();
}
ExchangeDwnClass exchange = new ExchangeDwnClass();
private void button3_Click(object sender, EventArgs e)
{
if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
exchange.Path = path;
pathTxt.Text = path;
}
}
private void onBtn_Click(object sender, EventArgs e)
{
exchange.Username = userTxt.Text;
exchange.Password = passwdTxt.Text;
exchange.FilterSender = fromFilterTxt.Text;
exchange.EmailFetch = Convert.ToInt32(fetchUpDown.Value);
exchange.Exchange = exchangeTxt.Text;
exchange.GetAttachments();
}
private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterExcelCheck.CheckState == CheckState.Checked)
{
exchange.FilterExcel = ".xlsx";
}
else
{
exchange.FilterExcel = "";
}
}
private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterCSVCheck.CheckState == CheckState.Checked)
{
exchange.FilterCsv = ".csv";
}
else
{
exchange.FilterCsv = "";
}
}
private void exchangeTxt_MouseHover(object sender, EventArgs e)
{
tipLbl.Visible = true;
tipLbl.Text = "It is usually same as email address...";
}
private void exchangeTxt_MouseLeave(object sender, EventArgs e)
{
tipLbl.Visible = false;
}
//("\n" + CurrentDate.ToString() + " , Message id: " + ID + " , Message subject: " + Subject + " , Attachment name: " + AttachementName + "\r");
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//e.Result = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
//private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// if (e.Cancelled)
// {
// logOutputTxt.Text = "Thread is somehow cancelled, please contact developer for this issue...!";
// }
// else if (e.Error != null)
// {
// logOutputTxt.Text = e.Error.Message;
// }
// else
// {
// logOutputTxt.Text += e.Result;
// }
//}
}
}
as you can see I'm calling background worker from class ExchangeDwnClass which I believe is OK, by using:
form.backgroundWorker1.RunWorkerAsync();
and when I run debugger it really jumps to background worker
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
for some reason Form textbox control is not refreshing output.
p.s. I have created also on RunWorkerCompleted method but also without luck...
Any clue how can I work things out?
OK, the problem was that I have created another object in form ExchangeDowClass for Form1, instead of passing a reference object into method GetAttachments
complete code for Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string subject = "";
public string attachment = "";
public string date = "";
public string sender = "";
public Form1()
{
InitializeComponent();
}
ExchangeDwnClass exchange = new ExchangeDwnClass();
BackgroundWorker bgrWorker = new BackgroundWorker();
private void button3_Click(object sender, EventArgs e)
{
if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
exchange.Path = path;
pathTxt.Text = path;
}
}
private void onBtn_Click(object sender, EventArgs e)
{
exchange.EmailFetch=Convert.ToInt32(fetchUpDown.Value);
exchange.FilterSender = fromFilterTxt.Text;
exchange.Exchange = exchangeTxt.Text;
exchange.Password = passwdTxt.Text;
exchange.Username = userTxt.Text;
backgroundWorker1.RunWorkerAsync();
}
private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterExcelCheck.CheckState == CheckState.Checked)
{
exchange.FilterExcel = ".xlsx";
}
else
{
exchange.FilterExcel = "";
}
}
private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterCSVCheck.CheckState == CheckState.Checked)
{
exchange.FilterCsv = ".csv";
}
else
{
exchange.FilterCsv = "";
}
}
private void exchangeTxt_MouseHover(object sender, EventArgs e)
{
tipLbl.Visible = true;
tipLbl.Text = "It is usually same as email address...";
}
private void exchangeTxt_MouseLeave(object sender, EventArgs e)
{
tipLbl.Visible = false;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//logOutputTxt.Text += "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r"
//backgroundWorker1.ReportProgress(0);
exchange.GetAttachments(this);
}
private void Form1_Load(object sender, EventArgs e)
{
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
logOutputTxt.Text += "\n" + date + " , Sender: "+sender+" , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
}
}
}
and for ExchangeDwnClass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Exchange;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using System.Threading;
namespace DownloadAttachmentExchange
{
class ExchangeDwnClass
{
private string path_ = "";
private string filterSender_ = "";
private string subject_ = "";
private string id_ = "";
private string username_ = "";
private string password_ = "";
private string exchange_ = "";
private string filterExcel_ = "";
private string filterCSV_ = "";
private string attachmentName_ = "";
private int emailFetch_ = 0;
private DateTime current_;
ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
public string Path
{
get { return path_; }
set { path_ = value; }
}
public string FilterSender
{
get { return filterSender_; }
set { filterSender_ = value; }
}
public string Subject
{
get { return subject_; }
set { subject_ = value; }
}
public string ID
{
get { return id_; }
set { id_ = value; }
}
public string Username
{
get { return username_; }
set { username_ = value; }
}
public string Password
{
get { return password_; }
set { password_ = value; }
}
public string Exchange
{
get { return exchange_; }
set { exchange_ = value; }
}
public string FilterExcel
{
get { return filterExcel_; }
set { filterExcel_ = value; }
}
public string FilterCsv
{
get { return filterCSV_; }
set { filterCSV_ = value; }
}
public string AttachementName
{
get { return attachmentName_; }
set { attachmentName_ = value; }
}
public int EmailFetch
{
get { return emailFetch_; }
set { emailFetch_ = value; }
}
public DateTime CurrentDate
{
get { return current_; }
set { current_ = value; }
}
public void GetAttachments(Form1 form)
{
try
{
serv.Credentials = new WebCredentials(Username, Password);
serv.AutodiscoverUrl("username#domain.lan");
ItemView view = new ItemView(EmailFetch);
FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));
if (result != null && result.Items != null && result.Items.Count > 0)
{
foreach (Item item in result.Items)
{
EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
if (msg.Sender.ToString().ToLower().Contains(FilterSender) && msg.From.ToString().ToLower().Contains(FilterSender))
{
foreach (Attachment att in msg.Attachments)
{
if (att is FileAttachment)
{
FileAttachment file = att as FileAttachment;
if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
{
file.Load(Path +"\\"+ file.Name);
form.attachment = file.Name.ToString();
form.subject = item.Subject.ToString();
//ID = item.Id.ToString();
form.date = DateTime.Now.ToString();
form.sender = msg.Sender.ToString();
form.backgroundWorker1.ReportProgress(0);
Thread.Sleep(60000);
}
}
}
}
//item.Delete(DeleteMode.HardDelete);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public void StopDownloadingAttachment()
{
}
}
}
Plus I had to use ProgressChanged method to refresh control...
I still have some minor bugs like double output in textbox form, but this is basically small issue.
I hope this code will be useful to others.
Cheers.

Directory created by C# program thread is locked

I have this program that creates threads on which i must create queue folders and
check them for files.
Now I noticed my program failed after processing a huge number of files without problems.
I produces a UnauthorizedAccessException so I went looking for that folder and it appears
the folder has been locked out totally?!
Could this be my anti-virus blocking access or is it something I must fix on my thread?
public class worker
{
public bool Stopping = false;
private System.Timers.Timer _timer;
private List<string> _files;
#region Feedback
public event FeedbackHandler Feedback;
public delegate void FeedbackHandler(object sender, string text);
#endregion
#region Properties
private string _name;
public string Name
{
get { return _name; }
}
private string _folder;
public string Folder
{
get { return _folder; }
set { _folder = value; }
}
private string _outfolder = Path.Combine(shared.Root, "out");
public string Outfolder
{
get { return _outfolder; }
set { _outfolder = value; }
}
private string _backupfolder = Path.Combine(shared.Root, "backup");
public string Backupfolder
{
get { return _backupfolder; }
set { _backupfolder = value; }
}
private string _filter = "*.*";
public string Filter
{
get { return _filter; }
set { _filter = value; }
}
private SearchOption _subfolders = SearchOption.TopDirectoryOnly;
public bool Subfolders
{
get { return (_subfolders == SearchOption.AllDirectories); }
set { if (value) { _subfolders = SearchOption.AllDirectories; } else { _subfolders = SearchOption.TopDirectoryOnly; } }
}
#endregion
#region Constructor
public worker(string Name)
{
_name = Name;
_folder = Path.Combine(shared.Root, "queues");
_folder = Path.Combine(_folder, Name);
}
#endregion
#region Destructor
~worker()
{
}
#endregion
#region Control
public void Start()
{
Stopping = false;
Directory.CreateDirectory(_folder);
_timer = new System.Timers.Timer(1);
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
Feedback(this, "[" + _name + "] started!");
}
public void Stop()
{
Stopping = true;
Feedback(this, "[" + _name + "] stopped...");
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (Stopping)
{
_timer.Stop();
_files.Clear();
return;
}
_timer.Stop();
Process();
_timer.Start();
}
#endregion
void Process()
{
if (Directory.Exists(_folder))
{
_files = Directory.GetFiles(_folder, _filter, _subfolders).ToList();
foreach (string _file in _files.ToArray())
{
if (Stopping) { break; }
document _document = new document(_file);
_document.Copy(_backupfolder);
_document.Move(_outfolder);
}
_files = new List<string>();
}
}
}
public class document
{
private string _header;
#region Feedback
public event FeedbackHandler Feedback;
public delegate void FeedbackHandler(object sender, string text);
#endregion
#region Properties
private string _file;
public string File
{
get { return _file; }
}
private job _job;
public job Job
{
get { return _job; }
}
#endregion
#region Constructor
public document(string File)
{
_file = File;
_header = shared.FileOperations.ReadHeader(_file);
_job = new job(_file, _header);
_job.ReadHeader();
}
#endregion Constructor
public void Copy(string Folder)
{
string _backupfile;
_backupfile = Path.Combine(Folder,_job.Name);
_backupfile = Path.Combine(_backupfile,_job.Company);
_backupfile = Path.Combine(_backupfile, DateTime.Now.ToString("yyyy"));
_backupfile = Path.Combine(_backupfile, DateTime.Now.ToString("MMMM"));
Directory.CreateDirectory(_backupfile);
_backupfile = Path.Combine(_backupfile, Path.GetFileName(_file));
shared.FileOperations.CopyFile(_file, _backupfile, true);
}
public void Move(string Folder)
{
string _outfile;
_outfile = Path.Combine(Folder, Path.GetFileNameWithoutExtension(_file));
shared.FileOperations.MoveFile(_file, _outfile, true);
}
}
public struct shared
{
public static string Root
{
get
{
string _base = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
return Directory.GetParent(_base).Parent.FullName.ToString();
}
}
public struct Patterns
{
public const string Header = #"\^?JOB\s(?<JOB>[a-zA-Z0-9]+[0-9]{3})[D]?(?<ACTION>[JFE]+)(?<COMPANY>[A-Z]{2,2})\s" +
#"(?<EMAIL>-emto=.*)?" +
#"-C(?<COPIES>[0-9]{2,2})\s" +
#"-Z""(?<PRINTER>[A-Z0-9]+)""\s" +
#"(?:\^?PAGE 01|(?<FAX>\^?FAX.*)\s\^?PAGE 01?)";
public const string Jump = #"\^PAGE\s[0-9]+";
public const string Pages = #"(\$?PAGE\s)";
public const string Fax = #"\^?FAX FROM_COMPANY\s""(?<FROM>.*)""\s" +
#"\^?FAX FROM_FAX_NUM\s""(?<FFAX>.*)""\s" +
#"\^?FAX FROM_NAME\s""(?<FNAME>.*)""\s" +
#"\^?FAX TO_FAX_NUM\s""(?<TFAX>.*)""\s" +
#"\^?FAX TO_COMPANY\s""(?<TO>.*)""\s" +
#"\^?FAX TO_NAME\s""(?<TNAME>.*)""\s" +
#"\^?FAX WHO\s""(?<WHO>.*)""\s" +
#"\^?FAX ID\s+(?<ID>.*)";
public const string Mail = #"-em([^\s=]+)=(""[^""]*""|[^\s]+)";
public const string Seperator = #"^";
}
public struct FileOperations
{
// Encoding
public static Encoding ReadEncoding = Encoding.GetEncoding(1252);
public static Encoding WriteEncoding = Encoding.UTF8;
// Timeouts
static int Timeout = 1;
static int FileTimeout = 10000; // 10 seconds/file permitted..
// Header
public static string ReadHeader(string SourceFile)
{
return ReadHeader(SourceFile, Patterns.Jump);
}
public static string ReadHeader(string SourceFile, string Beacon)
{
WaitFile(SourceFile);
string r = null;
string l = null;
try
{
StreamReader _reader = new StreamReader(SourceFile, ReadEncoding);
Match _match;
do
{
l = _reader.ReadLine();
r += l + " ";
_match = Regex.Match(l, Beacon);
} while (!_match.Success);
_reader.Close();
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
return r;
}
// Read Contents
public static List<string> ReadFile(string SourceFile)
{
return ReadFile(SourceFile, Patterns.Seperator);
}
public static List<string> ReadFile(string SourceFile, string Seperator)
{
WaitFile(SourceFile);
List<string> lines = new List<string>();
try
{
StreamReader sr = new StreamReader(SourceFile, Encoding.GetEncoding(1250));
string tmp = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
if (!string.IsNullOrEmpty(line) && line.Substring(0, 1) == Seperator)
{
if (!string.IsNullOrEmpty(tmp))
{
lines.Add(tmp);
}
tmp = line.Replace(Seperator, "^");
}
else
{
tmp += Environment.NewLine + line;
}
}
sr.Close();
if (!string.IsNullOrEmpty(tmp))
{
lines.Add(tmp);
}
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) {throw ex;}
}
return lines;
}
// Write Contents
public static void WriteFile(string DestinationFile, List<string> Lines)
{
try
{
File.WriteAllLines(DestinationFile, Lines.ToArray(), WriteEncoding);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
public static void WriteFile(string DestinationFile, string Contents)
{
try
{
File.WriteAllText(DestinationFile, Contents);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
// Move File
public static void MoveFile(string SourceFile, string DestinationFile, bool Overwrite)
{
WaitFile(SourceFile);
try
{
string _count = null;
string _destination = Path.GetDirectoryName(DestinationFile);
string _file = Path.GetFileNameWithoutExtension(DestinationFile);
string _extension = Path.GetExtension(DestinationFile);
string[] _files = Directory.GetFiles(_destination, _file + "*");
if (_files.Length > 0)
{
if (Overwrite)
{
for (int x = 0; x <= _files.Length - 1; x++)
{
File.Delete(_files[x]);
}
}
else
{
_count = "_" + (_files.Length - 1).ToString("D4");
}
}
DestinationFile = Path.Combine(_destination, _file + _count + _extension);
File.Move(SourceFile, DestinationFile);
}
catch (Exception ex)
{
if (Debugger.IsAttached) { throw ex; }
}
}
public static void CopyFile(string SourceFile, string DestinationFile, bool Overwrite)
{
WaitFile(SourceFile);
try
{
string _count = null;
string _destination = Path.GetDirectoryName(DestinationFile);
string _file = Path.GetFileNameWithoutExtension(DestinationFile);
string _extension = Path.GetExtension(DestinationFile);
string[] _files = Directory.GetFiles(_destination, _file + "*");
if (_files.Length > 0)
{
if (Overwrite)
{
for (int x = 0; x <= _files.Length - 1; x++)
{
File.Delete(_files[x]);
}
}
else
{
_count = "_" + (_files.Length - 1).ToString("D4");
}
}
DestinationFile = Path.Combine(_destination, _file + _count + _extension);
File.Copy(SourceFile, DestinationFile);
}
catch (Exception ex)
{
if (Debugger.IsAttached) { throw ex; }
}
}
// Delete File
public static void DeleteFile(string SourceFile)
{
WaitFile(SourceFile);
try
{
File.Delete(SourceFile);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
// Check File
static void WaitFile(string SourceFile)
{
Timeout = 1;
while (!File.Exists(SourceFile))
{
System.Threading.Thread.Sleep(Timeout);
Timeout++;
if (Timeout == FileTimeout)
{
// todo
if (Debugger.IsAttached) { throw new Exception("Timout exceeded!"); }
}
}
Timeout = 1;
while (!IsFileReady(SourceFile))
{
System.Threading.Thread.Sleep(Timeout);
Timeout++;
if (Timeout == FileTimeout)
{
// todo
if (Debugger.IsAttached) { throw new Exception("Timout exceeded!"); }
}
}
}
static bool IsFileReady(String SourceFile)
{
try
{
using (FileStream inputStream = File.Open(SourceFile, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
}
public struct Functions
{
public static string CleanXML(string Text)
{
Text = Text.Replace(#"&", #"&");
Text = Text.Replace(#"<", #"<");
Text = Text.Replace(#">", #">");
Text = Text.Replace(#"""", #""");
Text = Text.Replace(#"'", #"&apos;");
return Text;
}
}
}
void Work(string Name)
{
_worker = _workers.FirstOrDefault(w => w.Name == Name);
if (_worker == null)
{
_worker = new worker(Name);
_worker.Feedback+=new worker.FeedbackHandler(Feedback);
_worker.Folder = Path.Combine(_queuefolder, Name);
_worker.Outfolder = _outfolder;
_worker.Backupfolder = _backupfolder;
_workers.Add(_worker);
Thread _thread = new Thread(_worker.Start);
_thread.Start();
_thread.Join();
}
}
To clarify what i meant:
//worker class
private volatile bool _stopping;
private Thread _thread;
public void Start()
{
_stopping = false;
Directory.CreateDirectory(_folder);
_thread = new Thread(Process);
_thread.Start();
Feedback(this, "[" + _name + "] started!");
}
public void Stop()
{
_stopping = true;
_thread.Join();
Feedback(this, "[" + _name + "] stopped...");
}
private void Process()
{
while(!_stopping)
{
......
Thread.Sleep(100);
}
}
Because the way you are using timers... It's wrong. And while its interesting to know, why windows locks the folder, you should start from doing some refactoring. It might actually solve your problem along the way.

Categories

Resources