Search code examples
c#winformswindows-servicessetup-projectopenfiledialog

File doesn't upload windows form C#


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

Solution

  • This is working for me, I have made the following changes:

    1. Use Task.Factory.StartNew instead of Task.Run
    2. Added some logic for combining paths.

    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.