I create a windows service and a setup project. I create a windows form to upload a file for my setup project.
My issue is when I click on my file to upload it, my file doesn't upload. And the form doesn't close too.
ProjectInstaller of my windows service
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
Form1 validationForm = new Form1(Context.Parameters["TARGETDIR"]);
validationForm.ShowDialog();
}
Windows form
private static string folderToUploadFile = string.Empty;
public Form1(string folder)
{
InitializeComponent();
folderToUploadFile = folder;
label1.Text = folder;
}
private void button1_Click_1(object sender, EventArgs e)
{
var task = new Thread(() => {
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var filename = fileDialog.FileName;
Task.Run(() =>
{
File.Copy(filename, folderToUploadFile);
this.Close();
});
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
task.SetApartmentState(ApartmentState.STA);
task.Start();
task.Join();
}
This is working for me, I have made the following changes:
Your button click should look something like this.
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
//fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var fullPath = fileDialog.FileName;
var fileName = Path.GetFileName(fullPath);
var destination = Path.Combine(folderToUploadFile, fileName);
Task.Factory.StartNew(() =>
{
File.Copy(fullPath, destination);
this.Close();
});
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Please be aware manually copying files to the install directory, will mean they remain after an uninstall, so you may wish to handle this.
EDIT:
You don't actually need the Task.Factory.StartNew().... Task.Run should work the same.