Esempio n. 1
0
    private static void TreverseDir(DirectoryInfo dir)
    {

        var currentFolder = new CustomFolder(dir.Name);
        folderStructure.Add(currentFolder);
        var folders = dir.GetDirectories();
        var files = dir.GetFiles();

        try
        {
            foreach (var file in files)
            {
                var currentFile = new CustomFile(file.Name, file.Length);
                currentFolder.AddFile(currentFile);
            }

            foreach (var folder in folders)
            {
                var childFolder = new CustomFolder(folder.Name);

                currentFolder.AddFolder(childFolder);
                TreverseDir(folder);
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Access denied! ");
        }
    }
Esempio n. 2
0
        public ObservableCollection <CustomFile> GetCustomFiles(string path)
        {
            ObservableCollection <CustomFile> customFiles = new ObservableCollection <CustomFile>();
            var dirinfo = new DirectoryInfo(path);

            try
            {
                foreach (var customFile in dirinfo.GetFiles())
                {
                    var file = new CustomFile
                    {
                        Name        = customFile.FullName,
                        ShortName   = customFile.FullName.Remove(0, customFile.FullName.LastIndexOf("\\") + 1),
                        DateCreated = customFile.CreationTime,
                        Type        = Path.GetExtension(customFile.FullName),
                        Size        = customFile.Length / 512 + " KB",
                    };

                    //CustomDirectory.Items.Add(file);
                    customFiles.Add(file);
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                System.Console.WriteLine("Got Exception");
            }
            return(customFiles);
        }
Esempio n. 3
0
        /// <summary>
        /// The file URL.
        /// </summary>
        /// <param name="relativeFilePath">The relative file path.</param>
        /// <param name="withCDNResolving">if set to <c>true</c> [with CDN resolving].</param>
        /// <returns></returns>
        public virtual IHtmlString FileUrl(string relativeFilePath, bool withCDNResolving)
        {
            Site       site = this.Site;
            var        dir  = Path.GetDirectoryName(relativeFilePath);
            CustomFile file;

            if (string.IsNullOrEmpty(dir))
            {
                file = new CustomFile(site, relativeFilePath);
            }
            else
            {
                CustomDirectory customDir = new CustomDirectory(site, dir).LastVersion();
                file = new CustomFile(customDir, Path.GetFileName(relativeFilePath));
            }
            file = file.LastVersion();
            if (withCDNResolving)
            {
                return(ResourceCDNUrl(file.VirtualPath));
            }
            else
            {
                return(new HtmlString(Url.Content(file.VirtualPath)));
            }
        }
Esempio n. 4
0
        public void Write(string path, CustomFile file)
        {
            try
            {
                string directory = Path.GetDirectoryName(path);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate), System.Text.Encoding.Default))
                {
                    writer.Write(TypeToByte <Header>(file.Header));
                    writer.Flush();

                    foreach (TradeRecord trade in file.Trades)
                    {
                        writer.Write(TypeToByte <TradeRecord>(trade));
                        writer.Flush();
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 5
0
        public IEnumerable <CustomFile> AllEnumerable(CustomDirectory dir)
        {
            List <CustomFile> list = new List <CustomFile>();
            var baseDir            = dir.PhysicalPath;

            if (Directory.Exists(baseDir))
            {
                //output directory
                foreach (var folder in IO.IOUtility.EnumerateDirectoriesExludeHidden(baseDir))
                {
                    var customFile = new CustomFile();
                    customFile.Site     = dir.Site;
                    customFile.FileType = "Folder";

                    customFile.Name      = folder.Name;
                    customFile.Directory = new CustomDirectory(dir, customFile.Name);
                    list.Add(customFile);
                }
                //output files
                foreach (var file in IO.IOUtility.EnumerateFilesExludeHidden(baseDir))
                {
                    var customFile = new CustomFile(file.FullName);
                    customFile.Site      = dir.Site;
                    customFile.Directory = new CustomDirectory(dir, customFile.Name);
                    list.Add(customFile);
                }
            }
            return(list);
        }
Esempio n. 6
0
        public void UpdateObject(CustomFile file)
        {
            CheckDirectory();

            var storageFileInfo = this.GetStorageFileInfo(file.BlobName);

            this.SerializeCustomFile(storageFileInfo.PhysicalFileName, file);
        }
Esempio n. 7
0
 private void SerializeCustomFile(string filePath, CustomFile customFile)
 {
     using (var stream = File.Open(GetFullPath(filePath), FileMode.Create))
     {
         var binaryFormatter = new BinaryFormatter();
         binaryFormatter.Serialize(stream, customFile);
     }
 }
Esempio n. 8
0
        public string Add()
        {
            this.DocumentUrl   = CustomFile.SaveDocumentFile(this.DocumentFileBase, "MedicineReport", this.Id, "MedicineReport");
            this.ComplainantId = AuthenticatedUserModel.GetUserFromIdentity().Id;
            var newId = _medicineReportService.Add(this);

            _medicineService.MedicineReportInc(this.MedicineInfoId);
            return(newId);
        }
Esempio n. 9
0
        public static CustomFile GenerateLargeTestFile(int contentSize)
        {
            var generatedString = RandomString(contentSize);

            var fileContent = Encoding.Unicode.GetBytes(generatedString);

            var customFile = new CustomFile(Guid.NewGuid() + ".testfile", fileContent);

            return(customFile);
        }
Esempio n. 10
0
        public void TestPhysicalPath()
        {
            var    site      = new Site("Site1");
            string imageName = "image1.jpg";
            var    image     = new CustomFile(site, imageName);

            string expected1 = Path.Combine(site.PhysicalPath, "files", imageName);

            Assert.AreEqual(expected1, image.PhysicalPath, true);
        }
Esempio n. 11
0
        public void TestVirtualPath()
        {
            var    site      = new Site("Site1");
            string imageName = "image1.jpg";
            var    image     = new CustomFile(site, imageName);

            string expected1 = Kooboo.Web.Url.UrlUtility.Combine(site.VirtualPath, "files", imageName);

            Assert.AreEqual(expected1, image.VirtualPath, true);
        }
        public void Init()
        {
            string dbName = "data.db";

#if UNITY_EDITOR || UNITY_IOS || UNITY_STANDALONE
            string appDbPath = string.Format("{0}/{1}", GetStreamingPath(), dbName);
#else
            string appDbPath = string.Format("{0}/{1}", Application.persistentDataPath, dbName);
            if (!File.Exists(appDbPath))
            {
                //用www先从Unity中下载到数据库
                string tempProjectDbPath = string.Format("{0}/{1}", GetStreamingPath(), dbName);
                WWW    loadDB            = new WWW(tempProjectDbPath);
                while (!loadDB.isDone)
                {
                }

                //拷贝至规定的地方
                File.WriteAllBytes(appDbPath, loadDB.bytes);
                loadDB.Dispose();
            }
            else
            {
                //用www先从Unity中下载到数据库
                string tempProjectDbPath = string.Format("{0}/{1}", GetStreamingPath(), dbName);
                WWW    loadDB            = new WWW(tempProjectDbPath);
                while (!loadDB.isDone)
                {
                }

                string tempStr1 = CustomFile.GetFileHash(appDbPath);
                string tempStr2 = CustomFile.GetBytesHash(loadDB.bytes);

                if (tempStr1 != tempStr2)
                {
                    Debuger.Log("字节不同,重新写入数据");
                    File.WriteAllBytes(appDbPath, loadDB.bytes);
                }
                loadDB.Dispose();
            }
#endif
            if (Application.isMobilePlatform && Application.platform == RuntimePlatform.Android)
            {
                string tempPath = string.Format("URI = file:{0}", appDbPath);
                dbAccess = new SQLiteHelper(tempPath);
            }
            else
            {
                string tempPath = string.Format("data source={0}", appDbPath);
                dbAccess = new SQLiteHelper(tempPath);
            }
        }
Esempio n. 13
0
        public void AddObject(CustomFile file)
        {
            CheckDirectory();

            var filePath = $"{Guid.NewGuid()}{this.FileExtension}";

            this.SerializeCustomFile(filePath, file);
            this.Indexes.Add(new StorageFileInfo
            {
                PhysicalFileName = filePath,
                BlobName         = file.BlobName
            });
        }
Esempio n. 14
0
        public void TestParseFromPhysicalPath()
        {
            string siteName     = "site1";
            string imageName    = "image1";
            string extension    = ".jpg";
            string physicalPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sites", siteName, "files", imageName + extension);

            var imageFile = new CustomFile(physicalPath);

            Assert.AreEqual(imageName, imageFile.Name);
            Assert.AreEqual(extension, imageFile.FileExtension);

            Assert.AreEqual(siteName, imageFile.Site.Name);
        }
Esempio n. 15
0
        public async Task <ActionResult> Compress(string name, [FromForm] IFormFile file)
        {
            //try
            //{
            CustomFile result       = new CustomFile();
            Huffman    compression  = new Huffman();
            string     path         = _env.ContentRootPath;
            string     originalName = file.FileName;
            double     originalSize;

            using (var Memory = new MemoryStream())
            {
                if (file != null && name != null)
                {
                    await file.CopyToAsync(Memory);
                }
                else
                {
                    return(StatusCode(500));
                }
                using (FileStream stream = System.IO.File.Create(path + "/Uploads/" + originalName))
                {
                    stream.Write(Memory.ToArray());
                    stream.Close();
                }

                byte[] ByteArray = compression.Compress(path + "/Uploads/" + originalName, originalName, 100);
                originalSize = Memory.Length;
                double compressedSize = ByteArray.Length;



                compression.UpdateCompressions(path, originalName, path, originalSize, compressedSize);
                result.FileBytes   = ByteArray;
                result.contentType = "text / plain";
                result.FileName    = name;
                return(File(result.FileBytes, result.contentType, result.FileName + ".huff"));
            }


            //}
            //    catch (Exception)
            //    {

            //        return StatusCode(500);
            //}
        }
Esempio n. 16
0
        public void PostTestPositiv()
        {
            string       path         = "test files/test.dat";
            string       fullPath     = Regex.Replace(Path.GetFullPath(path), @"([^\\])\\([^\\])", m => m.Groups[1].Value + @"\\" + m.Groups[2].Value);
            string       formatCsv    = "csv";
            string       formatSQLite = "db";
            BinaryHelper binaryHelper = new BinaryHelper();

            CustomFile file = new CustomFile();

            file.Header = new Header()
            {
                version = 1,
                type    = "dat"
            };

            for (int i = 0; i < 5; i++)
            {
                file.Trades.Add(new TradeRecord()
                {
                    id      = i,
                    account = i * 2,
                    volume  = i * 2.2,
                    comment = "new"
                });
            }

            binaryHelper.Write(path, file);

            string stringForCsv     = string.Format("{{Path: '{0}', Format: '{1}'}}", fullPath, formatCsv);
            string stringForSQLite  = string.Format("{{Path: '{0}', Format: '{1}'}}", fullPath, formatSQLite);
            var    contentForCsv    = new StringContent(stringForCsv, Encoding.UTF8, "application/json");
            var    contentForSQLite = new StringContent(stringForSQLite, Encoding.UTF8, "application/json");

            Task <HttpResponseMessage> resultPostCsv = client.PostAsync(string.Format("{0}/api/file", url), contentForCsv);

            resultPostCsv.Wait();

            Task <HttpResponseMessage> resultPostSQLite = client.PostAsync(string.Format("{0}/api/file", url), contentForSQLite);

            resultPostSQLite.Wait();

            Assert.AreEqual(HttpStatusCode.Accepted, resultPostCsv.Result.StatusCode);
            Assert.AreEqual(HttpStatusCode.Accepted, resultPostSQLite.Result.StatusCode);
        }
Esempio n. 17
0
        public async Task <IActionResult> AddFileAsync(IFormFile source, int category)
        {
            if (source == null || !FileManager.CheckFileType(source))
            {
                return(View("Category"));
            }
            CustomFile addedFile = new CustomFile();
            string     cat       = _context.Categories.FirstOrDefault(x => x.Id == category).Name;
            var        res       = await FileManager.SaveFile(Path.Combine(_hostingEnvironment.WebRootPath, "file", cat), source);

            addedFile.Source     = res;
            addedFile.CategoryId = category;

            addedFile.Extension = Path.GetExtension(addedFile.Source);
            _context.CustomFiles.Add(addedFile);
            _context.SaveChanges();
            return(View("Category"));
        }
Esempio n. 18
0
        public static void SaveToFile(object content, string folderPath, string name = null)
        {
            try
            {
                var xmlContent = ObjectToXml(content);

                var filePath = string.Format("~/{0}/", folderPath);
                var fileName = name ?? string.Format("XML {0}.xml", AppSettings.ServerTime.ToString("yyyy_MM_dd_HH_mm"));

                var outputXML = new CustomFile(xmlContent);
                outputXML.SaveOnClient(fileName, filePath);
                outputXML.Delete();
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// The file URL.
        /// </summary>
        /// <param name="relativeFilePath">The relative file path.</param>
        /// <returns></returns>
        public virtual IHtmlString FileUrl(string relativeFilePath)
        {
            Site       site = this.PageRequestContext.Site;
            var        dir  = Path.GetDirectoryName(relativeFilePath);
            CustomFile file;

            if (string.IsNullOrEmpty(dir))
            {
                file = new CustomFile(site, relativeFilePath);
            }
            else
            {
                CustomDirectory customDir = new CustomDirectory(site, dir).LastVersion();
                file = new CustomFile(customDir, Path.GetFileName(relativeFilePath));
            }
            file = file.LastVersion();
            return(ResourceCDNUrl(file.VirtualPath));
        }
Esempio n. 20
0
        public bool Update()
        {
            try
            {
                this.DoctorChamberRelations   = this.ChamberSelectedIdsToDoctorChamberRelations().ToList();
                this.DoctorSpecialtyRelations = this.SpecialtySelectedIdsToDoctorSpecialtyRelations().ToList();
                this.DoctorDegreeRelations    = this.DegreeSelectedIdsToDoctorDegreeRelations().ToList();
                this.ImageUrl = CustomFile.SaveImageFile(this.ImageFileBase,
                                                         AuthenticatedDoctorUserModel.GetUserFromIdentity().Name,
                                                         AuthenticatedDoctorUserModel.GetUserFromIdentity().Id, "Doctor");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }

            return(_doctorService.Update(this));
        }
 private void CompressionAndDisplay()
 {
     try
     {
         CustomFile selectedFile         = (CustomFile)mW.ctrChildView.Custom.Items.Single(item => item.ShortName.Equals(textField.Text) && item.Type != "File folder");
         string     newCompressionedFile = CompressSelectedFile(selectedFile);
         mW.ctrChildView.Custom.Items.Add(new CustomFile
         {
             Name        = newCompressionedFile,
             ShortName   = Path.GetFileNameWithoutExtension(newCompressionedFile) + ".zip",
             Size        = new FileInfo(newCompressionedFile).Length / 512 + " KB",
             Type        = Path.GetExtension(newCompressionedFile),
             DateCreated = new FileInfo(newCompressionedFile).CreationTime,
         });
     }
     catch (InvalidOperationException)
     {
         MessageBox.Show("File not found", "Alert", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Esempio n. 22
0
        public void Load(BinaryReader reader)
        {
            // Clear custom files
            CustomFiles.Clear();

            // Get number of custom files
            int count = reader.ReadInt32();

            for (int i = 0; i < count; i++)
            {
                // Get custom file
                CustomFile customFile = CustomFile.Parse(reader);

                // If custom file is scored, add custom file to list
                if (customFile.IsScored)
                {
                    CustomFiles.Add(customFile);
                }
            }
        }
Esempio n. 23
0
        public virtual ActionResult Create(CustomFile model, string fullName)
        {
            Msg msg = new Msg();

            try
            {
                var userFile = Request.Files["image"];
                if (userFile.InputStream.Length == 0)
                {
                    throw new FriendlyException("Please select a file!");
                }
                Manager.SaveFile(this.Site, fullName, userFile.FileName, userFile.InputStream);
                return(RedirectToAction("Index", new { fullName = fullName }));
            }
            catch (FriendlyException e)
            {
                ModelState.AddModelError("", e.Message);
                return(View());
            }
        }
Esempio n. 24
0
        public virtual ActionResult File(string name)
        {
            var        dir = Path.GetDirectoryName(name);
            CustomFile file;

            if (string.IsNullOrEmpty(dir))
            {
                file = new CustomFile(Site, name);
            }
            else
            {
                CustomDirectory customDir = new CustomDirectory(Site, dir).LastVersion();
                file = new CustomFile(customDir, Path.GetFileName(name));
            }
            file = file.LastVersion();
            if (file.Exists())
            {
                SetCache(Response, 2592000, "*");
                return(File(file.PhysicalPath, IOUtility.MimeType(file.PhysicalPath)));
            }
            return(null);
        }
Esempio n. 25
0
        public CustomFile GetXlsxFile()
        {
            var weatherList = _weatherData.GetWeather();

            var filePath = $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\\Downloads\\Pogoda.xlsx";

            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Pogoda");

            ws.Cell(1, 1).Value = "Dzień";
            ws.Cell(1, 2).Value = "Dzień tygodnia";
            ws.Cell(1, 3).Value = "Średnia temperatura";
            ws.Cell(1, 4).Value = "Wiatr";
            ws.Cell(1, 5).Value = "Zachmurzenie";
            ws.Cell(1, 6).Value = "Opady";
            ws.Cell(1, 7).Value = "Ciśnienie";
            ws.Cell(1, 8).Value = "Promieniowanie UV";
            ws.Cell(2, 1).Value = weatherList.AsEnumerable();

            ws.Range(1, 1, 1, 8).AddToNamed("Titles");
            var titlesStyle = wb.Style;

            titlesStyle.Font.Bold            = true;
            titlesStyle.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
            wb.NamedRanges.NamedRange("Titles").Ranges.Style = titlesStyle;
            ws.Columns().AdjustToContents();

            wb.SaveAs(filePath);

            var newFile = new CustomFile
            {
                FileContents = File.ReadAllBytes(filePath),
                ContentType  = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                FileName     = "Pogoda.xlsx"
            };

            return(newFile);
        }
        private string CompressSelectedFile(CustomFile selectedFile)
        {
            StreamReader sr = new StreamReader(selectedFile.Name);
            string       selectedFileContent = sr.ReadToEnd();

            sr.Close();

            string newCompressionedFilePath = $@"{selectedFile.Name.Replace(selectedFile.ShortName, "")}{GetTimestamp(DateTime.Now)}.zip";

            using (FileStream zipToCreate = new FileStream(newCompressionedFilePath, FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipToCreate, ZipArchiveMode.Create))
                {
                    ZipArchiveEntry newEntry = archive.CreateEntry(selectedFile.ShortName);
                    using (StreamWriter writer = new StreamWriter(newEntry.Open()))
                    {
                        writer.WriteLine(selectedFileContent);
                    }
                }
            }

            return(newCompressionedFilePath);
        }
Esempio n. 27
0
        public CustomFile GetTxtFile()
        {
            var weatherList = _weatherData.GetWeather();

            var filePath = $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\\Downloads\\Pogoda.txt";

            using (var sw = new StreamWriter(filePath))
            {
                foreach (var w in weatherList)
                {
                    sw.WriteLine(($"{w.Date}, {w.DayOfWeek}, {w.Temp}, {w.Wind}, {w.Clouds}, {w.Rain}, {w.Pressure}, {w.UV}"));
                }
            }

            var newFile = new CustomFile
            {
                FileContents = File.ReadAllBytes(filePath),
                ContentType  = "text/plain",
                FileName     = "Pogoda.txt"
            };

            return(newFile);
        }
Esempio n. 28
0
 public async Task <ActionResult> Decompress([FromForm] IFormFile file)
 {
     try
     {
         string  path         = _env.ContentRootPath;
         Huffman decompresser = new Huffman();
         byte[]  decompressedText;
         using (var Memory = new MemoryStream())
         {
             if (file != null)
             {
                 await file.CopyToAsync(Memory);
             }
             else
             {
                 return(StatusCode(500));
             }
             byte[] ByteArray = Memory.ToArray();
             decompressedText = decompresser.Decompress(ByteArray);
             string OriginalName = decompresser.Name;
             using (FileStream stream = System.IO.File.Create(path + "/Compressions/" + OriginalName))
             {
                 stream.Write(Memory.ToArray());
             }
             CustomFile result = new CustomFile();
             result.FileBytes   = decompressedText;
             result.contentType = "text/plain";
             result.FileName    = OriginalName;
             return(File(result.FileBytes, result.contentType, result.FileName));
         }
     }
     catch (Exception)
     {
         return(StatusCode(500));
     }
 }
Esempio n. 29
0
        private void AddFile()
        {
            try
            {
                MainWindow mainWindow = System.Windows.Application.Current.Windows.OfType <MainWindow>().FirstOrDefault();
                CustomItemWithCollection sourceItem      = Custom;
                CustomDirectory          customDirectory = mainWindow.ctrTreeView.trvMenu.SelectedItem as CustomDirectory;
                bool isExist = false;
                foreach (var file in Custom.Items)
                {
                    if (Path.GetFileNameWithoutExtension(file.Name).Equals("New file"))
                    {
                        isExist = true;
                    }
                }

                if (!isExist)
                {
                    string newFilePath = $"{customDirectory.Name}" + @"\New file.txt";
                    File.CreateText(newFilePath);
                    CustomFile item = new CustomFile {
                        Name = newFilePath, ShortName = @"New file.txt", DateCreated = DateTime.Now, Type = Path.GetExtension(newFilePath), Size = new FileInfo(newFilePath).Length / 512 + " KB"
                    };
                    Custom.Items.Add(item);
                }
                else
                {
                    MessageBox.Show("File name already exist", "Alert", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                isExist = false;
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("File name already exist", "Alert", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void openFile(CustomFile cfile)
        {
            WebResponse lenResponse = NewFtpConnection(UserAccount.RootURL + cfile.FullPath, "length");

            WebResponse readResponse = NewFtpConnection(UserAccount.RootURL + cfile.FullPath, "download");
            StreamReader reader = new StreamReader(readResponse.GetResponseStream());

            BinaryReader br = new BinaryReader(readResponse.GetResponseStream());
            byte[] buffer = br.ReadBytes((int)(lenResponse.ContentLength));

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentEncoding = reader.CurrentEncoding;

            switch (cfile.Extension)
            {
                case ".pdf":
                    Response.ContentType = "application/pdf";
                    break;
                case ".png":
                    Response.ContentType = "image/png";
                    break;
                case ".gif":
                    Response.ContentType = "image/gif";
                    break;
                case ".jpeg":
                    Response.ContentType = "image/jpeg";
                    break;
                case ".jpg":
                    Response.ContentType = "image/jpg";
                    break;
                case ".mp3":
                    UserAccount.AudioUrl = UserAccount.RootURL + cfile.FullPath;
                    Response.Redirect("Audio.aspx");
                    break;
                case ".mp4":
                    UserAccount.VideoUrl = UserAccount.RootURL + cfile.FullPath;
                    Response.Redirect("Video.aspx");
                    break;
            }

            Response.AddHeader("Content-Disposition", "inline; filename=" + cfile.Name);
            Response.BinaryWrite(buffer);
            readResponse.Close();
            lenResponse.Close();
            Response.End();
        }
        private void refresh()
        {
            fileDisplay.Items.Clear();
            CustomFile.List.Clear(); //these two lists are parallel/corresponding

            List<string> folderList = new List<string>();

            FtpWebResponse Response = NewFtpConnection(UserAccount.RootURL + getCurrentDirectory(), "listDetail");
            Stream ResponseStream = Response.GetResponseStream();
            StreamReader Reader = new StreamReader(ResponseStream);

            //Note to jason/peter, if you want to enable file types being shown to the user, its CustomFile.HideFileTypes
            //or alternatively CustomFile.displayName(false) (non static)

            if (string.IsNullOrEmpty(UserAccount.SearchString) && string.IsNullOrEmpty(UserAccount.SortString) && (string.IsNullOrEmpty(UserAccount.LimitString) || UserAccount.LimitString == "All") )
            {
                while (!Reader.EndOfStream)
                {
                    //leaving the old code here
                    //fileDisplay.Items.Add(truncateFileName(getFileName(Reader.ReadLine().ToString())));

                    string fullpath = getFullFilePath(truncateFileName(Reader.ReadLine().ToString())); //omg
                    //string fullpath = getFullFilePath(truncateFileName(getFileName(Reader.ReadLine().ToString())));
                    CustomFile cfile = CustomFile.AddNew(fullpath, DateTime.Now, 696969); //file creation time and size not implemented yet
                    string displayname = cfile.displayName(); //adds file type or not depending on setting
                    fileDisplay.Items.Add(displayname);
                }
            } else if (!string.IsNullOrEmpty(UserAccount.SortString) || UserAccount.SortString == "None")
            {
                Regex rx = new Regex(UserAccount.SortString);
                //List<string> ls = new List<String>();
                List<CustomFile> ls = new List<CustomFile>();
                while (!Reader.EndOfStream)
                {
                    //old code, still used for now
                    string fullName = getFileName(Reader.ReadLine().ToString());

                    string fullpath = getFullFilePath(truncateFileName(fullName));
                    //note to self: this cfile can't be added yet (look at ls.add and then the foreach below that)
                    //it would cause CustomFile.List to be ordered differently
                    CustomFile cfile = new CustomFile(fullpath, DateTime.Now, 999);

                    if (rx.Match(fullName).Success)
                    {
                        //fileDisplay.Items.Add(truncateFileName(fullName));
                        string displayname = cfile.displayName(); //adds file type or not depending on setting
                        fileDisplay.Items.Add(displayname);
                        CustomFile.List.Add(cfile);
                    }
                    else
                    {
                        //old
                        //ls.Add(truncateFileName(fullName));
                        ls.Add(cfile);
                    }
                }

                /*foreach (string s in ls)
                {
                    fileDisplay.Items.Add(s);
                }*/
                foreach (CustomFile cfile in ls)
                {
                    fileDisplay.Items.Add(cfile.displayName());
                    CustomFile.List.Add(cfile);
                }
            } else if (!string.IsNullOrEmpty(UserAccount.SearchString))
            {
                Regex rx = new Regex(txtSearch.Text);
                while (!Reader.EndOfStream)
                {
                    string fullName = getFileName(Reader.ReadLine().ToString());

                    if (fullName.Substring(0, 1) == "d")
                    {
                        FtpWebResponse subResponse = NewFtpConnection(UserAccount.RootURL + truncateFileName(fullName), "listDetail");
                        Stream subResponseStream = subResponse.GetResponseStream();
                        StreamReader subReader = new StreamReader(subResponseStream);

                        while (!subReader.EndOfStream)
                        {
                            string subName = truncateFileName(subReader.ReadLine().ToString());

                            if (rx.Match(subName).Success)
                            {
                                //fileDisplay.Items.Add(truncateFileName(fullName) + "/" + truncateFileName(subName));

                                string fullpath = truncateFileName(fullName) + "/" + truncateFileName(subName);
                                CustomFile cfile = CustomFile.AddNew(fullpath, DateTime.Now, 99999);
                                //this scenario is a little different because folders are shown
                                fileDisplay.Items.Add(truncateFileName(fullName) + "/" + cfile.displayName());
                            }
                        }
                    } else
                    {
                        string filename = truncateFileName(fullName);
                        if (rx.Match(filename).Success)
                        {
                            //fileDisplay.Items.Add(truncateFileName(fullName));

                            string fullpath = getFullFilePath(filename);
                            CustomFile cfile = CustomFile.AddNew(fullpath, DateTime.Now, 69);
                            fileDisplay.Items.Add(cfile.displayName());
                        }
                    }
                }
            } else
            {
                Regex rx = new Regex(UserAccount.LimitString);

                while (!Reader.EndOfStream)
                {
                    string fullName = getFileName(Reader.ReadLine().ToString());

                    if (rx.Match(fullName).Success || fullName.Substring(0, 1) == "d")
                    {
                        //fileDisplay.Items.Add(truncateFileName(fullName));

                        string fullpath = getFullFilePath(truncateFileName(fullName));
                        CustomFile cfile = CustomFile.AddNew(fullpath, DateTime.Now, 69);
                        fileDisplay.Items.Add(cfile.displayName());
                    }

                }
            }

            Response.Close();
            ResponseStream.Close();
            Reader.Close();
        }
        private void renameItem(CustomFile cfile, string renameto)
        {
            if (cfile.isFolder())
            {
                //don't let the user add a file extension
                renameto = renameto.Replace(".", "_"); //simply change it to show the user it's not possible, until errors are implemented
            }

            try
            {
                FtpWebRequest renamereq = (FtpWebRequest)WebRequest.Create(UserAccount.RootURL + cfile.FullPath);
                renamereq.Credentials = new NetworkCredential(UserAccount.Username, UserAccount.Password);
                renamereq.Method = WebRequestMethods.Ftp.Rename;
                renamereq.RenameTo = renameto;

                if (!renameto.Contains("."))
                {
                    //user has renamed "file.ext" to "someotherfile" and has forgot the extension
                    //implement a "change file type" feature seperately if this is required
                    renamereq.RenameTo += cfile.Extension;
                }

                renamereq.GetResponse();
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.GetType().ToString() + ": filename = " + cfile.name + ", renameto = " + renameto);
            }
        }
Esempio n. 33
0
 public void AddFile(CustomFile file)
 {
     this.Files.Add(file);
 }
Esempio n. 34
0
 public void Remove(CustomFile item)
 {
     throw new NotImplementedException();
 }
Esempio n. 35
0
 public CustomFileInfoVM(CustomFile file)
 {
     File = file;
 }
        protected void copyFile(CustomFile cfile, string newpath)
        {
            //This method is admittedly very poor but temporary, it relies on the client to transfer the data
            //from one place in the server to another
            FtpWebResponse downloadresp = NewFtpConnection(UserAccount.RootURL + cfile.FullPath, "download");
            Stream downStream = downloadresp.GetResponseStream();

            MemoryStream ms = new MemoryStream();
            byte[] chunk = new byte[4096];
            int bytesRead;
            while ((bytesRead = downStream.Read(chunk, 0, chunk.Length)) > 0)
            {
                ms.Write(chunk, 0, bytesRead);
            }

            byte[] filebytes = ms.ToArray();
            ms.Close();

            string newfileurl = UserAccount.RootURL + newpath;

            FtpWebRequest uprequest = (FtpWebRequest)WebRequest.Create(newfileurl);
            uprequest.Credentials = new NetworkCredential(UserAccount.Username, UserAccount.Password);

            uprequest.KeepAlive = true;
            uprequest.UseBinary = true;
            uprequest.Method = WebRequestMethods.Ftp.UploadFile;

            Stream upstream = uprequest.GetRequestStream();
            upstream.Write(filebytes, 0, filebytes.Length);

            upstream.Close();
            downloadresp.Close();
            downStream.Close();
        }