Populates a T-SQL DB table from gathering all directory and file saved to specified directory on a local hard drive.
Below is the code that recursively retrieves all directory and file information from the /media/ directory:
1: public partial class Recursive : System.Web.UI.Page
2: {3: protected class Dirs
4: {5: public string name { get; set; }
6: public List<Filez> files { get; set; }
7: }8: protected class Filez
9: {10: public string name { get; set; }
11: public string ext { get; set; }
12: public string path { get; set; }
13: }14: List<Dirs> dirs = new List<Dirs>();
15: 16: protected void Page_Load(object sender, EventArgs e)
17: {18: recursive("/media/");
19: 20: } 21: 22: protected void recursive(string path)
23: {24: DirectoryInfo d = new DirectoryInfo(HttpContext.Current.Request.MapPath("~" + path));
25: Dirs tDirs = new Dirs();
26: tDirs.name = d.Name;27: string dStr = "";
28: foreach (var item in d.GetDirectories())
29: {30: dStr = path + item.Name + "/";
31: recursive(dStr); 32: }33: tDirs.files = d.GetFiles().Select(f => new Filez { name = f.Name, ext = f.Extension, path = path }).ToList();
34: dirs.Add(tDirs); 35: 36: } 37: }Using Linq-Entities framework, the gathered information is saved to the database by calling addToDB():
1: protected void addToDB()
2: {3: int width, height;
4: using (adminDBEntities contxt = new adminDBEntities())
5: {6: foreach (var item in dirs)
7: {8: foreach (var f in item.files)
9: { 10: width = 0; 11: height = 0;12: string path = HttpContext.Current.Request.MapPath("~" + f.path + f.name);
13: if (".jpg .png .gif .bmp".IndexOf(f.ext) != -1)
14: {15: using (System.Drawing.Image img = System.Drawing.Image.FromFile(path))
16: { 17: width = img.Width; 18: height = img.Height; 19: } 20: } 21: 22: MediaType mediaT = contxt.MediaTypes.Where(e => e.ext == f.ext).FirstOrDefault();23: if (mediaT != null)
24: {25: mediaT.Medias.Add(new Media
26: { 27: name = f.name, 28: path = f.path, 29: width = width, 30: height = height, 31: iDate = DateTime.Now, 32: uDate = DateTime.Now 33: }); 34: } 35: } 36: } 37: contxt.SaveChanges(); 38: } 39: }This blog is for my notes. Much of the code presented is work in process.
No comments:
Post a Comment