c#檔案上傳下載下傳功能實作
NuGet 安裝SqlSugar
Model檔案下建立 DbContext 類
```c#
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表的常用操作
### uploading實體類
```c#
[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; }
}
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<string> GetName(string name)
{
List<string> data = Db.Queryable<uploading>()
.Where(w=>w.name== name)
.Select(f => f.path)
.ToList();
return data;
}
}
### 窗體加載
讀取到資料庫字段name并指派
```c#
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;
}
for (int i = 0; i < data.Count; i++)
{
textBox1.Text = data[0];
}
}
### 上傳事件觸發
```c#
private void Button1_Click(object sender, EventArgs e)
{
string path = textBox1.Text;
CopyDirs(textBox3.Text,
path);
}
### 下載下傳事件觸發
```c#
private void Button2_Click(object sender, EventArgs e)
{
CopyDir(@"\\10.55.2.3\mech_production_line_sharing\Test\" + textBox2.Text, textBox4.Text);
}
private void CopyDir(string srcPath, string aimPath)
{
// 檢查目标目錄是否以目錄分割字元結束如果不是則添加
if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
aimPath += System.IO.Path.DirectorySeparatorChar;
}
// 判斷目标目錄是否存在如果不存在則建立
if (!System.IO.Directory.Exists(aimPath))
{
System.IO.Directory.CreateDirectory(aimPath);
}
// 得到源目錄的檔案清單,該裡面是包含檔案以及目錄路徑的一個數組
// 如果你指向copy目标檔案下面的檔案而不包含目錄請使用下面的方法
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
// 周遊所有的檔案和目錄
foreach (string file in fileList)
{
// 先當作目錄處理如果存在這個目錄就遞歸Copy該目錄下面的檔案
if (System.IO.Directory.Exists(file))
{
CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
DisplaylistboxMsg("下載下傳成功");
}
// 否則直接Copy檔案
else
{
System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
DisplaylistboxMsg("下載下傳成功");
}
}
}