獲取上次開啟目錄
阿新 • • 發佈:2020-07-30
路徑簡單儲存到csv檔案的方式,下次直接獲取
public class FolderPathHelper { public static string GetLastPath(string user, string menu) { string currentPath = Directory.GetCurrentDirectory() + "\\UserPath\\LastPath.csv"; if (!File.Exists(currentPath)) {return ""; } var table = OpenCSVFile(currentPath); var folder = table.AsEnumerable().FirstOrDefault(row => row["user"].ToString() == user && row["menu"].ToString() == menu)?["folder"].ToString() ?? ""; return folder; } publicstatic bool SavePath(string user, string menu, string folder) { //判斷目錄是否存在 string currentPath = Directory.GetCurrentDirectory() + "\\UserPath\\LastPath.csv"; DataTable table; table = OpenCSVFile(currentPath); if (table.Rows.Count > 0) { var rows = table.AsEnumerable().Where(row => row["user"].ToString() == user && row["menu"].ToString() == menu).ToList(); foreach (var row in rows) { table.Rows.Remove(row); } } table.Rows.Add(user, menu, folder, DateTime.Now.ToString("yyyyMMdd hhmmss")); SaveCSV(table, currentPath); return true; } public static void SaveCSV(DataTable dt, string fullPath)//table資料寫入csv { System.IO.FileInfo fi = new System.IO.FileInfo(fullPath); if (!fi.Directory.Exists) { fi.Directory.Create(); } using (System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write)) using(System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8)) { for (int i = 0; i < dt.Rows.Count; i++) //寫入各行資料 { var data = new List<string>(); for (int j = 0; j < dt.Columns.Count; j++) { var str = dt.Rows[i][j].ToString(); //替換英文冒號 英文冒號需要換成兩個冒號 str = str.Replace("\"", "\"\""); //含逗號 冒號 換行符的需要放到引號中 if (str.Contains(',') || str.Contains('"') || str.Contains('\r') || str.Contains('\n')) { str = $"\"{str}\""; } data.Add(str); } sw.WriteLine(string.Join(",",data)); } sw.Close(); fs.Close(); } } private static DataTable OpenCSVFile(string filepath) { string strpath = filepath; //csv檔案的路徑 var table = new DataTable(); table.Columns.Add("user"); table.Columns.Add("menu"); table.Columns.Add("folder"); table.Columns.Add("time"); if (!File.Exists(filepath)) { return table; } string strline; string[] aryline; using (StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default)) { while ((strline = mysr.ReadLine()) != null) { aryline = strline.Split(new char[] { ',' }); var row = table.NewRow(); for (int i = 0; i < table.Columns.Count; i++) { row[i] = aryline[i]; } table.Rows.Add(row); } return table; } } }