【问题标题】:File doesn't upload windows form C#文件不上传Windows表单C#
【发布时间】:2020-01-31 11:39:24
【问题描述】:

我创建了一个 Windows 服务和一个安装项目。 我创建了一个 Windows 窗体来为我的安装项目上传文件。

我的问题是当我点击我的文件上传时,我的文件没有上传。 而且表单也不会关闭。

我的 windows 服务的 ProjectInstaller

public override void Install(IDictionary stateSaver)
{
    base.Install(stateSaver);

    Form1 validationForm = new Form1(Context.Parameters["TARGETDIR"]);
    validationForm.ShowDialog();
}

Windows 窗体

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

【问题讨论】:

  • 您看到任何错误吗?尝试删除 File.Copy 和 this.Close() 周围的 Task.Run
  • @RyanThomas 没有错误,如果我删除 Task.Run 我的 windows 窗体的状态没有响应
  • 不使用 Task.Run - 如果您使用 Task.Factory.StartNew,它是否有效?另外我认为您可能需要在 folderToUploadFile 的末尾添加一个文件名
  • 另外请注意,手动将文件复制到安装目录意味着它们不会被卸载删除。

标签: c# winforms windows-services setup-project openfiledialog


【解决方案1】:

这对我有用,我做了以下更改:

  1. 使用 Task.Factory.StartNew 而不是 Task.Run
  2. 添加了一些组合路径的逻辑。

您的按钮点击应该如下所示。

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

请注意手动将文件复制到安装目录,这意味着它们在卸载后仍然存在,因此您可能希望处理此问题。

编辑:

您实际上并不需要 Task.Factory.StartNew().... Task.Run 应该可以工作。

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2011-04-02
    • 2014-04-29
    • 2019-06-30
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多