首页 > 解决方案 > 选择文件并将其上传到特定文件夹

问题描述

我需要将一个选定的文件上传到特定文件夹。我有这个代码:

using System.IO;

namespace FTP_UPLOAD
{
    public partial class FTPUPLOAD : Form
    {
        public FTPUPLOAD()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            var fileContent = string.Empty;
            var filePath = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "c:\\";
                openFileDialog.Filter = "zip files (*.zip)|*.zip";
                openFileDialog.FilterIndex = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //Get the path of specified file
                    filePath = openFileDialog.FileName;

                    //Read the contents of the file into a stream
                    var fileStream = openFileDialog.OpenFile();
                    {
                    }
                }
            }
            MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
        }
    }
}

我需要定义文件将上传到的位置(如 c:\ftp)。该过程完成后,我想向用户显示该文件所在位置的完整路径,例如(filename = file.zip)而不是:ftp.mysite/file.zip

标签: c#

解决方案


获取要保存的文件的路径后,需要使用 SaveFileDialog 类。添加using System.IO;以使用 FileInfo 类。

private void SaveFile(string filePath)
{
  FileInfo file = new FileInfo(filePath);

  using (SaveFileDialog saveFileDialog = new SaveFileDialog())
  {
    saveFileDialog.FileName = filePath;
    if( saveFileDialog.ShowDialog() == DialogResult.OK)
    {
      MessageBox.Show("Your file was saved at " + saveFileDialog.FileName);
    }                
  }
}

推荐阅读