Get last opened directory

Time:2020-9-23

The path is simply saved to the CSV file, and is directly obtained next time.

Call method:

try
{
      dialog.SelectedPath  = FolderPathHelper.GetLastPath ("9009", "menu 1");
}
 catch (Exception ex)
 {
      Log ($"failed to get path:{ ex.ToString ()}");
#if DEBUG
      throw ex;
#endif
}
try
{
     FolderPathHelper.SavePath ("9009", "menu 1", "C: \");
}
catch (Exception ex)
{
      Log ($"failed to save path:{ ex.ToString ()}");
#if DEBUG
       throw ex;
#endif
}

Classes saved and retrieved:

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

        public static bool SavePath(string user, string menu, string folder)
        {
            //Determine whether the directory exists
            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) // write data to 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 + +) // write all lines of data
                {
                    var data = new List();
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        var str = dt.Rows[i][j].ToString();
                        //Replace English colons. English colons need to be replaced by two colons
                        str = str.Replace("\"", "\"\"");
                        //Those with commas, colons, newlines need to be enclosed in quotation marks
                        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; // path of the CSV file
            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;
            }
        }
    }