private static void Main(string[] args) { string pathToInputFiles = MyFile.GetFullFolderNameInApplicationTree("Input"); string pathToOutputFiles = MyFile.GetFullFolderNameInApplicationTree("Output"); const string teachersFileName = "Teachers.csv"; const string detailsFileName = "Details.csv"; const string ignoredTeachersFileName = "IgnoredTeachers.csv"; const string resultFileName = "Sprechstunden.html"; Console.WriteLine("Meet the teacher"); Console.WriteLine("================"); string inputFileName = Path.Combine(pathToInputFiles, teachersFileName); string[] teacherLines = File.ReadAllLines(inputFileName, Encoding.UTF8); string[] detailLines = File.ReadAllLines(Path.Combine(pathToInputFiles, detailsFileName), Encoding.UTF8); string[] ignoredNames = File.ReadAllLines(Path.Combine(pathToInputFiles, ignoredTeachersFileName), Encoding.UTF8); Controller ctrl = new Controller(teacherLines, detailLines, ignoredNames); throw new NotImplementedException("Ausgabe lt. Angabe (siehe Screenshots) implementieren!"); string html = ctrl.GetHtmlTable(); File.WriteAllText(Path.Combine(pathToOutputFiles, resultFileName), html, Encoding.Default); }
public static MyFile CreateFileMenu() { MyFile file = new MyFile(); Console.WriteLine("请输入笔记名:"); string name = Console.ReadLine() + ".txt"; //Console.WriteLine("请输入存储路径:(示例:C:\\Users\\11393\\Desktop\\C#)"); //string path = Console.ReadLine() + "\\"; Console.WriteLine("请输入文件分类:"); Category category = new Category(); //string pa = category.ShowCategory("D:\\"); Console.WriteLine("请输入笔记内容:(以#号键结束)"); string content = ""; string s = Console.ReadLine(); while (!s.Equals("#")) { content += s; s = Console.ReadLine(); } //file.Path = pa; file.Name = name; file.Content = content; return(file); }
/// <summary> /// Liest die Buchungen mit ihren Räumen und Kunden aus der /// csv-Datei ein. /// </summary> /// <returns></returns> public static async Task <IEnumerable <Booking> > ReadBookingsFromCsvAsync() { List <Customer> customers = (await MyFile.ReadStringMatrixFromCsvAsync("bookings.csv", true)) .Select(c => new Customer { LastName = c[0], FirstName = c[1], Iban = c[2] }) .ToList() ; List <Room> rooms = (await MyFile.ReadStringMatrixFromCsvAsync("bookings.csv", true)) .Select(c => new Room { RoomNumber = c[3] }) .ToList() ; List <Booking> bookings = (await MyFile.ReadStringMatrixFromCsvAsync("bookings.csv", true)) .Select(b => new Booking { Customer = customers.Where(c => c.LastName.Equals(b[0]) && c.FirstName.Equals(b[1]) && c.Iban.Equals(b[2])).FirstOrDefault(), Room = rooms.Where(r => r.RoomNumber.Equals(b[3])).FirstOrDefault(), From = b[4], To = b[5] }) .ToList(); return(bookings); }
/// <summary> /// Liefert die Messwerte mit den dazugehörigen Sensoren /// </summary> public static Commit[] ReadFromCsv() { string[][] commitsArray = MyFile.ReadStringMatrixFromCsv(FilenameCsv, false); var devs = commitsArray.GroupBy(c => c[0]) .Select(c => new Developer { Name = c.Key, Commits = new List <Commit>() }).ToDictionary(n => n.Name); var commits = commitsArray.Select(c => new Commit { Developer = devs[c[0]], Date = DateTime.Parse(c[1]), HashCode = c[2], Message = c[3], FilesChanges = int.Parse(c[4]), Insertions = int.Parse(c[5]), Deletions = int.Parse(c[6]) }).ToArray(); foreach (var item in commits) { item.Developer.Commits.Add(item); } return(commits); }
public Controller(string[] inputFileNames, string holidayFileName) { _inputFilePath = MyFile.GetFullFolderNameInApplicationTree("input"); InitHolidays(holidayFileName); InitMeasurements(inputFileNames); }
/// <summary> /// Сериализация всех обьектов Базы данных. Клиенты, Администраторы, Тренеры, Расписание груповых тренировок /// </summary> public static void SerializeObjects() { MyFile.CreateFolder(Options.FolderNameDataBase); var currentPath = Directory.GetCurrentDirectory() + "\\" + Options.FolderNameDataBase; lock (Locker) { SerializeClass.Serialize(_dataBaseList, currentPath + "\\" + Options.PersonsDbFile); // Журнал посещений SerializeClass.Serialize(_visitsDictionary, currentPath + "\\" + Options.PersonVisitsDbFile); // История Абонементов SerializeClass.Serialize(_abonHistoryDictionary, currentPath + "\\" + Options.PersonAbonHistDbFile); // База Тренеров SerializeClass.Serialize(_trenersList, currentPath + "\\" + Options.TrenersDbFile); // База Администраторов SerializeClass.Serialize(_adminsList, currentPath + "\\" + Options.AdminsDbFile); // Текущий Администратор на Ресепшн SerializeClass.Serialize(_manhattanInfo.CurrentAdmin, currentPath + "\\" + Options.AdminCurrFile); // Список названий всех ежедневных Групповых Тренировок SerializeClass.Serialize(_groupScheduleList, currentPath + "\\" + Options.GroupSchFile); // Сериализация списков посещений. Списки отображаются на главной форме(4 колонки) DailyVisits.GetInstance().Serialize(); } }
private void CreatTasks() { string taskPath = MyFile.GetFullNameInApplicationTree("Tasks.csv"); string[] taskLines = File.ReadAllLines(taskPath, UTF8Encoding.Default); OrderType orderType; Article article; for (int i = 1; i < taskLines.Length; i++) { string[] parts = taskLines[i].Split(';'); string guestName = parts[1]; Guest guest = new Guest(guestName); if (parts != null && Enum.TryParse(parts[2], out orderType)) { if (!_guestList.ContainsKey(guestName)) { _guestList.Add(guestName, guest); } DateTime taskTime = FastClock.Instance.Time.AddMinutes(Convert.ToInt32(parts[0])); Task taskOrder = new Task(taskTime, parts[1], orderType, parts[3]); _tasks.Add(taskOrder); if (orderType == OrderType.Order && _articles.TryGetValue(parts[3], out article)) { taskTime = taskTime.AddMinutes(article.TimeToBuild); Task taskReady = new Task(taskTime, taskOrder.Customer, OrderType.Ready, taskOrder.MyArticle); _tasks.Add(taskReady); } } } _tasks.Sort(); }
void OnShowContent(MyFile content) { switch (attribute) { case FileAttributes.Location: text.text = content.location; break; case FileAttributes.Date: text.text = content.date; break; case FileAttributes.Copyright: text.text = content.copyright; break; } if (background != null) { if (string.IsNullOrWhiteSpace(text.text)) { background.canvasRenderer.SetAlpha(0); } else { background.canvasRenderer.SetAlpha(1); } } // TODO low prio: languages }
/// <summary> /// Liest die Buchungen mit ihren Räumen und Kunden aus der /// csv-Datei ein. /// </summary> /// <returns></returns> public static async Task <IEnumerable <Booking> > ReadBookingsFromCsvAsync() { string[][] matrix = await MyFile.ReadStringMatrixFromCsvAsync("bookings.csv", true); var customers = matrix .GroupBy(line => line[0] + " " + line[1] + " " + line[2]) .Select(grp => new Customer() { LastName = grp.Key.Split(' ')[0], FirstName = grp.Key.Split(' ')[1], Iban = grp.Key.Split(' ')[2] }) .ToList(); var rooms = matrix .GroupBy(line => line[3]) .Select(grp => new Room() { RoomNumber = grp.Key }) .ToList(); Booking[] bookings = matrix .Select(line => new Booking() { Customer = customers.Single(cus => cus.LastName.Equals(line[0]) && cus.FirstName.Equals(line[1])), Room = rooms.Single(ro => ro.RoomNumber.Equals(line[3])), From = line[4], To = line[5] }) .ToArray(); return(bookings); }
public static IEnumerable <Game> ReadFromCsv() { string[][] data = MyFile.ReadStringMatrixFromCsv(Filename, false); var teams = data.GroupBy(d => d[HOMETEAM_IDX]) .Select(d => new Team { Name = d.Key, HomeGames = new List <Game>(), AwayGames = new List <Game>() }) .ToDictionary(_ => _.Name); var games = data.Select(d => new Game { Round = int.Parse(d[ROUND_IDX]), HomeTeam = teams[d[HOMETEAM_IDX]], GuestTeam = teams[d[GUESTTEAM_IDX]], HomeGoals = int.Parse(d[HOMETEAM_GOALS_IDX]), GuestGoals = int.Parse(d[GUESTTEAM_GOALS_IDX]) }) .ToArray(); foreach (var game in games) { game.GuestTeam.AwayGames.Add(game); game.HomeTeam.HomeGames.Add(game); } return(games); }
public FileView(MyFile discElement) { InitializeComponent(); this.discElement = discElement; NameBox.Text = discElement.GetName(); DateBox.Text = discElement.GetCreationTime().ToShortDateString(); }
private void buttonUnZip_Click(object sender, EventArgs e) { var items = explorer.SelectedItems; if (items.Count == 0) { return; } foreach (var item in items) { ListViewItem listItem = item as ListViewItem; if (listItem != null) { MyFile listItemAsMyFile = listItem.Tag as MyFile; if (listItemAsMyFile != null) { try { AskModelUnzipFile(listItemAsMyFile); } catch (Exception exc) { MessageBox.Show(exc.Message + " while Unzipping"); } } } } }
private void explorer_ItemActivate(object sender, EventArgs e) { var items = explorer.SelectedItems; foreach (var item in items) { ListViewItem listItem = item as ListViewItem; if (listItem != null) { if (listItem.Group.Name == "folder") { MyFolder folder = listItem.Tag as MyFolder; ModelChangeDirectory(folder); } else if (listItem.Group.Name == "file") { try { MyFile file = listItem.Tag as MyFile; AskModelExecuteFile(file); } catch (Exception exc) { MessageBox.Show(exc.Message + " while exectuing a file"); } } else if (listItem.Group.Name == "up") { ModelGoUp(); } } } }
// создание файлов private void Watcher_Created(object sender, FileSystemEventArgs e) { ThreadPool.QueueUserWorkItem(async state => { string fileName = e.Name; string filePath = e.FullPath; Console.WriteLine(fileName); string fileEvent = "создан"; Regex regex = new Regex(parsedOptions.options.PathsOptions.Regex); Console.WriteLine(fileName + " ||| " + regex.IsMatch(fileName)); if (regex.IsMatch(fileName)) { RecordEntry("вошли", fileName); await MyFile.EncryptFile(fileName, filePath, parsedOptions.options.EncryptingOptions.Key); await MyFile.CompressAndMove(fileName, filePath, parsedOptions.options.PathsOptions.TargetPath, parsedOptions.options.CompressOptions.Extension); await MyFile.DecompressFileToTargetDir(fileName, filePath, parsedOptions.options.CompressOptions.Extension); string newPath = MyFile.GetPathOfFileInTargetDir(fileName); newPath += fileName; await MyFile.DecryptFile(fileName, newPath, parsedOptions.options.EncryptingOptions.Key); } RecordEntry(fileEvent, fileName); }); }
public async Task <IActionResult> AddNews(News news, List <IFormFile> files) { if (ModelState.IsValid) { if (_dbContext.News.Where(p => p.Title.Equals(news.Title)).Count() == 0) { if (files.Count() > 0) { news.Images = new List <NewsImage>(); foreach (var f in files) { news.Images.Add(new NewsImage { Url = f.FileName, NewsId = news.Id, MimeType = f.ContentType }); } } string upPath = Path.Combine(_env.WebRootPath, "images"); MyFile.Up(upPath, files).Wait(); _dbContext.News.Add(news); await _dbContext.SaveChangesAsync(); TempData["Message"] = "添加成功!"; return(RedirectToAction(nameof(Index))); } } ViewData["errorMessage"] = "添加失败!"; return(View(news)); }
/// <summary> /// Liefert die Movies mit den dazugehörigen Kategorien /// </summary> public static IEnumerable <Movie> ReadFromCsv() { //var path = MyFile.GetFullFolderNameInApplicationTree(Filename); var path = MyFile.GetFullNameInApplicationTree(Filename); Dictionary <string, Category> categories = File.ReadAllLines(path) .Skip(1) .Select(s => s.Split(';')) .Select(s => s?[2]) .Distinct() .ToDictionary(s => s, s => new Category { CategoryName = s }); return(File.ReadAllLines(path) .Skip(1) .Select(s => s.Split(';')) .Select(s => new Movie() { Title = s?[0], Duration = int.Parse(s?[3]), Year = int.Parse(s?[1]), Category = categories.TryGetValue(s?[2], out Category category) ? category : new Category { CategoryName = s[2] } })
/// <summary> /// Liefert die Movies mit den dazugehörigen Kategorien /// </summary> public static IEnumerable <Movie> ReadFromCsv() { string[][] data = MyFile.ReadStringMatrixFromCsv(Filename, true); Dictionary <string, Category> categories = new Dictionary <string, Category>(); List <Movie> movies = new List <Movie>(); categories = data.GroupBy(c => c[CATEGORYNAME_IDX]) .Select(c => new Category { CategoryName = c.Key, Movies = new List <Movie>() }) .ToDictionary(_ => _.CategoryName); movies = data .Select(m => new Movie { Title = m[TITLE_IDX], Category = categories[m[CATEGORYNAME_IDX]], Duration = int.Parse(m[DURATION_IDX]), Year = int.Parse(m[YEAR_IDX]) }).ToList(); foreach (var m in movies) { categories[m.Category.CategoryName].Movies.Add(m); } return(movies); }
void OpenFile(MyFile file) { SelectFile(file); // openFile = file; onFileClicked?.Invoke(file); }
public static async Task <MemberSection[]> ReadFromCsvAsync() { var data = await MyFile.ReadStringMatrixFromCsvAsync(FileName, false); var sections = data.GroupBy(d => d[SECTION_IDX]) .Select(d => new Section() { Name = d.Key, MemberSections = new List <MemberSection>() }) .ToDictionary(x => x.Name); var members = data.GroupBy(data => data[LASTNAME_IDX] + "_" + data[FIRSTNAME_IDX]) .Select(d => new Member() { LastName = d.Key.Split("_")[LASTNAME_IDX], FirstName = d.Key.Split("_")[FIRSTNAME_IDX], MemberSections = new List <MemberSection>() }) .ToDictionary(x => x.LastName + "_" + x.FirstName); var memberSections = data.Select(d => new MemberSection() { Member = members[d[LASTNAME_IDX] + "_" + d[FIRSTNAME_IDX]], Section = sections[d[SECTION_IDX]] }).ToArray(); return(memberSections); }
public void FileToMongoToFileTrip() { // read test file // write it into MongoBd var docId = Guid.NewGuid().ToString(); ReadFileAndWriteItInMongo(docId); // Read it back var segments = ReadDocSegmentsFromMongo(docId); CleanUpMongo(docId); // and write into a file. const string targetFilePath = @"C:\Projects\GLD\HIPAA\GLD.HIPAA\GLD.HIPAA.Doc\Samples\GeneratedByTest.Sample.txt"; if (File.Exists(targetFilePath)) { File.Delete(targetFilePath); } MyFile.Write(targetFilePath, docId, segments); Assert.IsTrue(File.Exists(targetFilePath)); Assert.IsTrue(File.ReadAllLines(targetFilePath).Length > 1); }
private static async Task UploadStream(MyFile myFile, Stream stream) { try { using (HttpClient httpClient = new HttpClient()) // instance should be shared { httpClient.BaseAddress = new Uri("https://localhost:5000"); using (MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent()) { multipartFormDataContent.Add(new StringContent(JsonConvert.SerializeObject(myFile), Encoding.UTF8, "application/json"), nameof(MyFile)); // Here we add the file to the multipart content. // The third parameter is required to match the 'IsFileDisposition()' but could be anything multipartFormDataContent.Add(new StreamContent(stream), "stream", nameof(MyFile)); HttpResponseMessage httpResult = await httpClient.PostAsync("api/values/upload", multipartFormDataContent).ConfigureAwait(false); httpResult.EnsureSuccessStatusCode(); // We don't need any result stream anymore } } } catch (Exception e) { Console.WriteLine(e.Message); } }
public static IEnumerable <Book> ReadBooksFromCsv() { string[][] matrix = MyFile.ReadStringMatrixFromCsv("books.csv", false); var authors = matrix .SelectMany(line => line[0].Split('~')) .Distinct() .Select(text => new Author { Name = text }) .OrderBy(a => a.Name) .ToList(); var books = matrix .Select(line => new Book() { Title = line[1], Publishers = line[2], Isbn = line[3] }) .ToList(); var bookAuthors = matrix .SelectMany(line => line[0].Split('~'), (line, authorName) => new BookAuthor //line an der 0 wird gesplittet und ist der áuthorname zudem wird line mitgegeben damit an der stelle 3 die isbn verglichen werden kann { Author = authors.Single(a => a.Name == authorName), Book = books.Single(b => b.Isbn == line[3]) }) .ToList(); books.ForEach(book => book.BookAuthors = bookAuthors.Where(ba => ba.Book == book).ToList()); return(books); }
public static IEnumerable <Game> ReadFromCsv() { string[][] matrix = MyFile.ReadStringMatrixFromCsv("PremierLeague.csv", false); // keine Titelzeile // Einlesen der Spiele und der Teams // Zuerst die Teams var teams = matrix .Select(line => line[1]) .Union(matrix.Select(line => line[2])) .Distinct() .Select(text => new Team { Name = text }) .OrderBy(a => a.Name) .ToList(); var games = matrix .Select(line => new Game() { Round = int.Parse(line[0]), HomeTeam = teams.Single(t => t.Name == line[1]), GuestTeam = teams.Single(t => t.Name == line[2]), HomeGoals = int.Parse(line[3]), GuestGoals = int.Parse(line[4]) }) .ToList(); return(games); }
//通过指定的根目录返回文件列表 public List <MyFile> GetFilesByPath(string path) { List <MyFile> myfile = new List <MyFile>(); DirectoryInfo theFolder = new DirectoryInfo(path); DirectoryInfo[] dirInfo = theFolder.GetDirectories(); //遍历文件夹 foreach (DirectoryInfo NextFolder in dirInfo) { // this.listBox1.Items.Add(NextFolder.Name); FileInfo[] fileInfo = NextFolder.GetFiles(); foreach (FileInfo NextFile in fileInfo) //遍历文件 { MyFile fi = new MyFile(); fi.Name = NextFile.Name; fi.Path = path + "\\" + NextFile.Name + ".txt"; fi.Content = ""; if (File.Exists(fi.Path)) { List <string[]> list = new List <string[]>(); // 打开文件时 一定要注意编码 也许你的那个文件并不是GBK编码的 using (StreamReader sr = new StreamReader(fi.Path, System.Text.Encoding.GetEncoding("GBK"))) { while (!sr.EndOfStream) //读到结尾退出 { fi.Content = fi.Content + sr.ReadLine(); } } } myfile.Add(fi); } } return(myfile); }
public static async Task <MemberSection[]> ReadFromCsvAsync() { string[][] matrix = await MyFile.ReadStringMatrixFromCsvAsync(FileName, false); var member = matrix.Distinct() .Select(mem => new Member { LastName = mem[0], FirstName = mem[1] }).GroupBy(line => line.LastName + line.FirstName) .Select(s => s.First()).ToArray(); var section = matrix .GroupBy(line => line[2]) .Distinct() .Select(sec => new Section { Name = sec.Key }).ToArray(); var memberSection = matrix .Select(ms => new MemberSection { Member = member.Single(m => m.LastName == ms[0] && m.FirstName == ms[1]), Section = section.Single(s => s.Name == ms[2]) }).Distinct().ToArray(); return(memberSection); }
public void FillDb() { this.DeleteDatabase(); this.MigrateDatabase(); string[][] csvMovies = MyFile.ReadStringMatrixFromCsv(FILENAME, true); List <Category> categories = csvMovies.GroupBy(line => line[2]).Select(grp => new Category() { CategoryName = grp.Key }).ToList(); List <Movie> movies = csvMovies.Select(line => new Movie() { Category = categories.Single(cat => cat.CategoryName == line[2]), Duration = int.Parse(line[3]), Title = line[0], Year = int.Parse(line[1]), }).ToList(); _dbContext.Categories.AddRange(categories); _dbContext.Movies.AddRange(movies); Save(); }
public void CryptDecryptFileWithTrueKey() { // arrange MyFile file = Factory.CreateFile(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetRandomFileName())); file.FileAppendAllText("secretInfo123123"); List <Entry> entries = new List <Entry>(); entries.Add(file); string key = "key123"; // act FileSystemContainer container = new FileSystemContainer(entries, false, true); container.Accept(new DESCryptoVisitor(true, key)); MyFile cryptFile; if (Factory.TryGetFile(file.FullPath + "_crypted", out cryptFile)) { entries.Clear(); entries.Add(cryptFile); container = new FileSystemContainer(entries, false, true); container.Accept(new DESCryptoVisitor(false, key)); } else { Assert.Fail("File " + file.FullPath + " is crypted, but " + file.FullPath + "_crypted " + "could not be found!"); } string decryptResult = file.FileReadAllLines()[0]; file.Delete(); // assert Assert.AreEqual("secretInfo123123", decryptResult); }
/// <summary> /// Liefert die Messwerte mit den dazugehörigen Sensoren /// </summary> public static Measurement[] ReadFromCsv() { string[][] matrix = MyFile.ReadStringMatrixFromCsv(Filename, true); var sensors = matrix.GroupBy(line => line[2]) .Select(sensorGroup => { var parts = sensorGroup.Key.Split('_'); return(new Sensor { Name = parts[1], Location = parts[0] }); } ).ToArray(); var measurements = matrix .Select(line => new Measurement { Time = DateTime.Parse($"{line[0]} {line[1]}"), Sensor = sensors.Single(sensor => line[2] == $"{sensor.Location}_{sensor.Name}"), Value = double.Parse(line[3]) } ).ToArray(); return(measurements); }
private static void Main(string[] args) { string pathToInputFiles = MyFile.GetFullFolderNameInApplicationTree("Input"); string pathToOutputFiles = MyFile.GetFullFolderNameInApplicationTree("Output"); const string teachersFileName = "Teachers.csv"; const string detailsFileName = "Details.csv"; const string ignoredTeachersFileName = "IgnoredTeachers.csv"; const string resultFileName = "Sprechstunden.html"; Console.WriteLine("Meet the teacher"); Console.WriteLine("================"); string inputFileName = Path.Combine(pathToInputFiles, teachersFileName); string[] teacherLines = File.ReadAllLines(inputFileName, Encoding.UTF8); string[] detailLines = File.ReadAllLines(Path.Combine(pathToInputFiles, detailsFileName), Encoding.UTF8); string[] ignoredNames = File.ReadAllLines(Path.Combine(pathToInputFiles, ignoredTeachersFileName), Encoding.UTF8); Controller ctrl = new Controller(teacherLines, detailLines); string html = ctrl.GetHtmlTable(); Console.WriteLine("Hier ist der HTML CODE !!!"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(html); File.WriteAllText(Path.Combine(pathToOutputFiles, resultFileName), html, Encoding.Default); }
public MyFileInfo(MyFile file) { this.file = file; this.createTime = file.CreationTime; this.lastModifyTimeUtc = file.LastWriteTimeUtc; this.size = file.Length; }
//-------------------------------------------------------------------------------- //сохраняет файл public void DownloadFile(StreamWithProgress fileSourceStream, MyFile file ) { logger.Debug("Получение файла с сервера " + file.ToString()); string fileFullPath = StorageFolder + "\\" + file.Path + "\\" + file.Name; FileStream outputStream = GetFileStream(file.Path, file.Name); try { fileSourceStream.CopyTo(outputStream); fileSourceStream.Close(); } catch (IOException ex)// клиент закрыл поток { logger.Error("Сервер закрыл соединение. " + ex.Message); } outputStream.Close(); FileInfo savedFileInfo = new FileInfo(fileFullPath); logger.Debug("Исходный файл:{0}, Полученный файл:{1}", file.Size, savedFileInfo.Length); if (file.Size != savedFileInfo.Length) { logger.Error("Размер файл полученного файла не соответствует исходному. Полученный файл будет удален!"); } logger.Info("Сделано"); }
private static void MakeFileSystem(DirectoryInfo dir, MyFolder currentFolder) { foreach (FileInfo file in dir.GetFiles()) { var newFile = new MyFile(file.Name, file.Length); currentFolder.Files.Add(newFile); } foreach (DirectoryInfo subDir in dir.GetDirectories()) { var newDirectory = new MyFolder(subDir.Name); currentFolder.SubFolders.Add(newDirectory); MakeFileSystem(subDir, newDirectory); } }
public MyFolder(string name, MyFile[] files, MyFolder[] subFolders) { this.Name = name; this.Files = files; this.SubFolders = subFolders; }
//отправялет файл на сервер public void UploadFile(MyFile file, StreamWithProgress stream) { serverFileSystem.UploadFile(file, Account.GetUserEmail(), Account.GetUserPass(), stream); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IDefault page) { #region AtFile Action<File> AtFile = f => { var n = new MyFile(); // databind here? n.name.innerText = f.name; n.type.innerText = f.type; n.lastModifiedDate.innerText = "" + f.lastModifiedDate; #region hex new FileReader().With( reader => { reader.onload = IFunction.Of( delegate { var x = (ArrayBuffer)reader.result; var u8 = new Uint8Array(x, 0, 8); var pre = new IHTMLPre().AttachTo(n.Container); pre.style.border = "1px solid gray"; for (uint i = 0; i < u8.length; i++) { pre.innerText += u8[i].ToString("x2") + " "; } } ); // Read in the image file as a data URL. reader.readAsArrayBuffer(f); } ); #endregion #region AsDataURL Action<Action<string>> AsDataURL = h => { var reader = new FileReader(); reader.onload = IFunction.Of( delegate { var base64 = (string)reader.result; h(base64); } ); // Read in the image file as a data URL. reader.readAsDataURL(f); }; #endregion #region image if (f.type.StartsWith("image/")) { AsDataURL( base64 => new IHTMLImage { src = base64, }.AttachTo(n.Container) ); } #endregion #region audio if (f.type.StartsWith("audio/")) { AsDataURL( base64 => new IHTMLAudio { src = base64, controls = true, }.AttachTo(n.Container) ); } #endregion #region video //if (f.type.StartsWith("video/")) //{ // AsDataURL( // base64 => // new IHTMLVideo // { // src = base64, // controls = true, // }.AttachTo(n.Container) // ); //} #endregion n.Container.AttachTo(page.list); }; #endregion #region onchange page.files.onchange += e => { FileList x = page.files.files; page.list.Clear(); page.list.Add("files: " + x.length); for (uint i = 0; i < x.length; i++) { File f = x[i]; AtFile(f); } }; #endregion page.drop_zone.ondragleave += delegate { page.drop_zone.style.borderColor = JSColor.Gray; page.drop_zone.style.backgroundColor = JSColor.None; }; #region dragover page.drop_zone.ondragover += evt => { page.drop_zone.style.borderColor = JSColor.Red; page.drop_zone.style.backgroundColor = JSColor.FromRGB(0xff, 0xaf, 0xaf); evt.StopPropagation(); evt.PreventDefault(); evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy. }; page.drop_zone.ondrop += evt => { page.drop_zone.style.borderColor = JSColor.Green; page.drop_zone.style.backgroundColor = JSColor.FromRGB(0xaf, 0xff, 0xaf); evt.StopPropagation(); evt.PreventDefault(); FileList x = evt.dataTransfer.files; // FileList object. page.list.Clear(); page.list.Add("files: " + x.length); for (uint i = 0; i < x.length; i++) { File f = x[i]; AtFile(f); } }; #endregion }
//создание структуры MyFile с новым статусом private MyFile CreateFileWithChangeStatus(MyFile file, FileStatus status) { return new MyFile() { Name = file.Name, Path = file.Path, Size = file.Size, status = status, IsDirectory=file.IsDirectory, LastWriteTime = file.LastWriteTime, FileId = file.FileId }; }