c# 实现文件上传下载功能的实例代码

2020-07-02 12:59:59刘景俊

NuGet 安装SqlSugar

1.Model文件下新建 DbContext 类

 public class DbContext
  {
    public DbContext()
    {
      Db = new SqlSugarClient(new ConnectionConfig()
      {
        ConnectionString = "server=localhost;uid=root;pwd=woshishui;database=test",
        DbType = DbType.MySql,
        InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
        IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
    });
    //调式代码 用来打印SQL 
    Db.Aop.OnLogExecuting = (sql, pars) =>
    {
      Console.WriteLine(sql + "rn" +
               Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
      Console.WriteLine();
    };

  }
  //注意:不能写成静态的,不能写成静态的
  public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
  public SimpleClient<uploading> uploadingdb { get { return new SimpleClient<uploading>(Db); } }//用来处理Student表的常用操作
}

2.建uploading实体类

[SugarTable("uploading")]
  public class uploading
  {
  //指定主键和自增列,当然数据库中也要设置主键和自增列才会有效
  [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
  public int id { get; set; }
  public string name { get; set; }
  public string path { get; set; }
}

3.Manager文件下建UploadingManager

 class UploadingManager : DbContext
  {
    public List<uploading> Query()
    {
      try
      {
        List<uploading> data = Db.Queryable<uploading>()
          .Select(f => new uploading
          {
            name = f.name,
            path = f.path
          })
          .ToList();
        return data;
      }
      catch (Exception e)
      {
        Console.WriteLine(e);
        throw;
      }
  }

  public List&lt;string&gt; GetName(string name)
  {
    List&lt;string&gt; data = Db.Queryable&lt;uploading&gt;()
      .Where(w=&gt;w.name== name)
      .Select(f =&gt; f.path)
      .ToList();
    return data;

  }
}

窗体加载Form1_Load

1.读取到数据库字段name并赋值

 private void Form1_Load(object sender, EventArgs e)
    {
      List<uploading> data = uploading.Query();
      foreach (var data1 in data)
      {
        comboBox1.Items.Add(data1.name);
      }
      comboBox1.SelectedIndex = 0;
  }

2.comboBox事件触发条件查询到上传的path

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
      List<string> data = uploading.GetName(comboBox1.Text);
    for (int i = 0; i &lt; data.Count; i++)
    {
      textBox1.Text = data[0];
    }
  }

3.上传事件触发

 private void Button1_Click(object sender, EventArgs e)
    {
       string path = textBox1.Text;
      CopyDirs(textBox3.Text,
        path);
    }