Exemple #1
0
        public void TestSetAccessControl()
        {
            var filename = Util.CreateNewFile(longPathDirectory);

            try
            {
                var security = new FileSecurity();
                File.SetAccessControl(filename, security);
            }
            finally
            {
                File.Delete(filename);
            }
        }
Exemple #2
0
 public static void ClassInitialize(TestContext context)
 {
     rootTestDir       = context.TestDir;
     longPathDirectory = Util.MakeLongPath(rootTestDir);
     longPathRoot      = longPathDirectory.Substring(0, context.TestDir.Length + 1 + longPathDirectory.Substring(rootTestDir.Length + 1).IndexOf('\\'));
     Directory.CreateDirectory(longPathDirectory);
     Debug.Assert(Directory.Exists(longPathDirectory));
     longPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append(Filename).ToString();
     using (var writer = File.CreateText(longPathFilename))
     {
         writer.WriteLine("test");
     }
     Debug.Assert(File.Exists(longPathFilename));
 }
Exemple #3
0
        public void TestAppendAllTextEncoding()
        {
            var filename = Util.CreateNewFileUnicode(longPathDirectory);

            try
            {
                File.AppendAllText(filename, "test", Encoding.Unicode);
                Assert.AreEqual("beginning of file" + Environment.NewLine + "test", File.ReadAllText(filename, Encoding.Unicode));
            }
            finally
            {
                File.Delete(filename);
            }
        }
Exemple #4
0
        public void TestWriteAllLinesWithEncoding()
        {
            var tempLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("file26.ext").ToString();

            File.WriteAllLines(tempLongPathFilename, new string[] { "file26" }, Encoding.Unicode);
            try
            {
                Assert.AreEqual("file26" + Environment.NewLine, File.ReadAllText(tempLongPathFilename, Encoding.Unicode));
            }
            finally
            {
                File.Delete(tempLongPathFilename);
            }
        }
        public void DecryptAllVideos(string folderPath, Module module, string outputPath)
        {
            // Get all clips of this module from database
            List <Clip> listClips = module.Clips;

            if (listClips.Count > 0)
            {
                // integer to add 1 if index should start at 1
                int startAt1 = Convert.ToInt16(chkStartClipIndexAt1.Checked);
                foreach (Clip clip in listClips)
                {
                    // Get current path of the encrypted video
                    string currentPath = Path.Combine(folderPath, $"{clip.Name}.psv");
                    if (File.Exists(currentPath))
                    {
                        // Create new path with output folder
                        string newPath = Path.Combine(outputPath, $"{(startAt1 + clip.Index):00}. {clip.Title}.mp4");

                        // Init video and get it from iStream
                        var playingFileStream = new VirtualFileStream(currentPath);
                        playingFileStream.Clone(out IStream iStream);

                        string fileName = Path.GetFileName(currentPath);

                        bgwDecrypt.ReportProgress(1, new Log {
                            Text = $"Start to Decrypt File \"{fileName}\"", TextColor = Color.Yellow, NewLine = false
                        });

                        this.DecryptVideo(iStream, newPath);
                        if (chkCreateSub.Checked)
                        {
                            // Generate transcript file if user ask
                            this.WriteTranscriptFile(clip, newPath);
                        }

                        bgwDecrypt.ReportProgress(1, new Log {
                            Text = $"Decrypt File \"{Path.GetFileName(newPath)}\" success!", TextColor = Color.Green, NewLine = true
                        });
                        playingFileStream.Dispose();
                    }
                    else
                    {
                        bgwDecrypt.ReportProgress(1, new Log {
                            Text = $"File \"{Path.GetFileName(currentPath)}\"  cannot be found", TextColor = Color.Gray, NewLine = true, IsError = true
                        });
                    }
                }
            }
        }
Exemple #6
0
        public void TestReplaceIgnoreMergeWithReadonlyBackupPath()
        {
            var tempLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("filename.ext").ToString();
            var tempBackupPathName   = new StringBuilder(longPathDirectory).Append(@"\readonly").ToString();
            var di = new DirectoryInfo(tempBackupPathName);

            di.Create();

            var attr = di.Attributes;

            di.Attributes = attr | FileAttributes.ReadOnly;
            var tempBackupLongPathFilename = new StringBuilder(tempBackupPathName).Append(@"\").Append("backup").ToString();

            using (var fileStream = File.Create(tempLongPathFilename))
            {
                fileStream.WriteByte(42);
            }
            var tempLongPathFilename2 = new StringBuilder(longPathDirectory).Append(@"\").Append("filename2.ext").ToString();

            using (var fileStream = File.Create(tempLongPathFilename2))
            {
                fileStream.WriteByte(52);
            }
            try
            {
                const bool ignoreMetadataErrors = true;
                File.Replace(tempLongPathFilename, tempLongPathFilename2, tempBackupLongPathFilename, ignoreMetadataErrors);
                using (var fileStream = File.OpenRead(tempLongPathFilename2))
                {
                    Assert.AreEqual(42, fileStream.ReadByte());
                }
                Assert.IsFalse(File.Exists(tempLongPathFilename));
                Assert.IsTrue(File.Exists(tempBackupLongPathFilename));
            }
            finally
            {
                di.Attributes = attr;
                if (File.Exists(tempLongPathFilename))
                {
                    File.Delete(tempLongPathFilename);
                }
                File.Delete(tempLongPathFilename2);
                File.Delete(tempBackupLongPathFilename);
                if (Directory.Exists(tempBackupPathName))
                {
                    Directory.Delete(tempBackupPathName);
                }
            }
        }
        public frmMain()
        {
            InitializeComponent();
            #region Apply setting
            appSetting = File.Exists("setting.json") ? JsonConvert.DeserializeObject <AppSetting>(File.ReadAllText("setting.json")) : new AppSetting();

            if (string.IsNullOrEmpty(appSetting.CoursePath))
            {
                appSetting.CoursePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Pluralsight";
                if (!Directory.Exists(appSetting.CoursePath))
                {
                    appSetting.CoursePath = string.Empty;
                }

                txtCoursePath.Text = Directory.Exists(appSetting.CoursePath) ? appSetting.CoursePath + @"\courses" : "";
                txtDBPath.Text     = Directory.Exists(appSetting.CoursePath) ? appSetting.CoursePath + @"\pluralsight.db" : "";
                txtOutputPath.Text = Directory.Exists(appSetting.OutputPath) ? appSetting.OutputPath : "";
            }
            else
            {
                appSetting.CoursePath = Directory.Exists(appSetting.CoursePath) ? appSetting.CoursePath : "";
                txtCoursePath.Text    = Directory.Exists(appSetting.CoursePath) ? appSetting.CoursePath : "";
                txtDBPath.Text        = File.Exists(appSetting.DatabasePath) ? appSetting.DatabasePath : "";
                txtOutputPath.Text    = Directory.Exists(appSetting.OutputPath) ? appSetting.OutputPath : "";
            }



            chkDecrypt.Checked             = appSetting.Decrypt;
            chkCreateSub.Checked           = appSetting.CreateSub;
            chkDelete.Checked              = appSetting.DeleteAfterDecrypt;
            chkShowErrOnly.Checked         = appSetting.ShowErrorOnly;
            chkCopyImage.Checked           = appSetting.CopyImage;
            chkStartClipIndexAt1.Checked   = appSetting.ClipIndexAtOne;
            chkStartModuleIndexAt1.Checked = appSetting.ModuleIndexAtOne;
            #endregion

            imgList.ImageSize        = new Size(170, 100);
            imgList.ColorDepth       = ColorDepth.Depth32Bit;
            lsvCourse.LargeImageList = imgList;

            bgwDecrypt.DoWork             += BgwDecrypt_DoWork;
            bgwDecrypt.ProgressChanged    += BgwDecrypt_ProgressChanged;
            bgwDecrypt.RunWorkerCompleted += BgwDecrypt_RunWorkerCompleted;

            bgwGetCourse.DoWork             += BgwGetCourse_DoWork;
            bgwGetCourse.ProgressChanged    += BgwGetCourse_ProgressChanged;
            bgwGetCourse.RunWorkerCompleted += BgwGetCourse_RunWorkerCompleted;
        }
Exemple #8
0
        public void TestWriteAllBytes()
        {
            var tempLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("filename.ext").ToString();
            var expected             = new byte[] { 3, 4, 1, 5, 9, 2, 6, 5 };

            File.WriteAllBytes(tempLongPathFilename, expected);
            try
            {
                Assert.IsTrue(expected.SequenceEqual(File.ReadAllBytes(tempLongPathFilename)));
            }
            finally
            {
                File.Delete(tempLongPathFilename);
            }
        }
Exemple #9
0
        public void TestGetIsReadOnly()
        {
            var filename = Util.CreateNewFile(longPathDirectory);

            try
            {
                var fi = new FileInfo(filename);
                Assert.IsTrue(fi.Exists);
                Assert.IsFalse(fi.IsReadOnly);
            }
            finally
            {
                File.Delete(filename);
            }
        }
        public static void CopyFile(string from, string to)
        {
            string directoryName = Path.GetDirectoryName(to);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            // FileUtil.CopyFileOrDirectory(from, to);
            try {
                File.Copy(from, to, true);
            } catch (Exception ex) {
                //Debug.LogError (string.Format ("{0}: {1}", ex.Message, ex.StackTrace));
            }
        }
Exemple #11
0
        public void TestSetAccessControl()
        {
            var filename = Util.CreateNewFile(uncDirectory);

            try
            {
                var fi       = new FileInfo(filename);
                var security = new FileSecurity();
                fi.SetAccessControl(security);
            }
            finally
            {
                File.Delete(filename);
            }
        }
Exemple #12
0
        public void TestAppendAllLines()
        {
            var filename = Util.CreateNewFile(longPathDirectory);

            try
            {
                File.AppendAllLines(filename, new[] { "test1", "test2" });
                Assert.AreEqual("beginning of file" + Environment.NewLine + "test1" + Environment.NewLine + "test2" + Environment.NewLine,
                                File.ReadAllText(filename));
            }
            finally
            {
                File.Delete(filename);
            }
        }
Exemple #13
0
        public void TestGetLastWriteTimeUtc()
        {
            var filename = Util.CreateNewFile(longPathDirectory);

            try
            {
                var dateTime = File.GetLastWriteTimeUtc(filename);
                var fi       = new FileInfo(filename);
                Assert.AreEqual(fi.LastWriteTimeUtc, dateTime);
            }
            finally
            {
                File.Delete(filename);
            }
        }
Exemple #14
0
        public void ReadCourse(string coursePath, string dbPath)
        {
            try
            {
                if (Directory.Exists(coursePath) && this.InitDb(dbPath))
                {
                    bgwGetCourse.ReportProgress(1, new Log()
                    {
                        Text = "Getting course data . . .", TextColor = Color.Green, NewLine = true
                    });

                    List <string> folderList = Directory.GetDirectories(coursePath, "*", SearchOption.TopDirectoryOnly).ToList();
                    logger.Debug($"FolderList1: {folderList.Count}");
                    folderList = folderList.Where(r => Directory.GetDirectories(r, "*", SearchOption.TopDirectoryOnly).Length > 0).ToList();
                    logger.Debug($"FolderList2: {folderList.Count}");
                    listCourse = folderList.Select(r => new CourseItem()
                    {
                        CoursePath = r, Course = this.GetCourseFromDb(r)
                    }).Where(r => r.Course != null).OrderBy(r => r.Course.Title).ToList();
                    logger.Debug($"listCourse1: {listCourse.Count}");
                    listCourse = listCourse.Where(c => c.Course.IsDownloaded).ToList();
                    logger.Debug($"listCourse2: {listCourse.Count}");
                    foreach (CourseItem item in listCourse)
                    {
                        Image img = File.Exists(item.CoursePath + @"\image.jpg") ? Image.FromFile(item.CoursePath + @"\image.jpg") : new Bitmap(100, 100);

                        ListViewItem listItem = new ListViewItem()
                        {
                            ImageKey = item.Course.Name, Name = item.Course.Name, Text = item.Course.Title
                        };

                        bgwGetCourse.ReportProgress(1, new { Item = listItem, Image = img });
                    }

                    bgwGetCourse.ReportProgress(1, new Log()
                    {
                        Text = $"Complete! Total: {listCourse.Count} courses", TextColor = Color.Green, NewLine = true
                    });

                    bgwGetCourse.ReportProgress(100);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                logger.Error(ex);
            }
        }
Exemple #15
0
        public void TestSetLastAccessTimeUtc()
        {
            var filename = Util.CreateNewFile(longPathDirectory);

            try
            {
                DateTime dateTime = DateTime.UtcNow.AddDays(1);
                var      fi       = new FileInfo(filename);
                fi.LastAccessTimeUtc = dateTime;
                Assert.AreEqual(dateTime, File.GetLastAccessTimeUtc(filename));
            }
            finally
            {
                File.Delete(filename);
            }
        }
Exemple #16
0
        public void TestSetLastWriteTime()
        {
            var filename = Util.CreateNewFile(uncDirectory);

            try
            {
                DateTime dateTime = DateTime.Now.AddDays(1);
                var      fi       = new FileInfo(filename);
                fi.LastWriteTime = dateTime;
                Assert.AreEqual(dateTime, File.GetLastWriteTime(filename));
            }
            finally
            {
                File.Delete(filename);
            }
        }
Exemple #17
0
        public void TestCopyWithoutOverwriteAndExistingFile()
        {
            var destLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("filename (Copy).ext").ToString();

            File.Copy(longPathFilename, destLongPathFilename);

            try
            {
                Assert.IsTrue(File.Exists(destLongPathFilename));
                Assert.Throws <IOException>(() => File.Copy(longPathFilename, destLongPathFilename));
            }
            finally
            {
                File.Delete(destLongPathFilename);
            }
        }
Exemple #18
0
        public void TestSetCreationTimeUtc()
        {
            var filename = Util.CreateNewFile(longPathDirectory);

            try
            {
                DateTime dateTime = DateTime.UtcNow.AddDays(1);
                File.SetCreationTimeUtc(filename, dateTime);
                var fi = new FileInfo(filename);
                Assert.AreEqual(fi.CreationTimeUtc, dateTime);
            }
            finally
            {
                File.Delete(filename);
            }
        }
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            appSetting = new AppSetting()
            {
                CoursePath         = txtCoursePath.Text,
                DatabasePath       = txtDBPath.Text,
                OutputPath         = txtOutputPath.Text,
                Decrypt            = chkDecrypt.Checked,
                CreateSub          = chkCreateSub.Checked,
                DeleteAfterDecrypt = chkDelete.Checked,
                ClipIndexAtOne     = chkStartClipIndexAt1.Checked,
                ModuleIndexAtOne   = chkStartModuleIndexAt1.Checked
            };

            File.WriteAllText("setting.json", JsonConvert.SerializeObject(appSetting));
        }
 public void DecryptVideo(IStream currentStream, string newPath)
 {
     try
     {
         currentStream.Stat(out STATSTG stat, 0);
         IntPtr myPtr      = (IntPtr)0;
         int    streamSize = (int)stat.cbSize;
         byte[] streamInfo = new byte[streamSize];
         currentStream.Read(streamInfo, streamSize, myPtr);
         File.WriteAllBytes(newPath, streamInfo);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #21
0
        public void TestReadAllBytes()
        {
            var tempLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("filename.ext").ToString();

            using (var fileStream = File.Create(tempLongPathFilename))
            {
                fileStream.WriteByte(42);
            }
            try
            {
                Assert.IsTrue(new byte[] { 42 }.SequenceEqual(File.ReadAllBytes(tempLongPathFilename)));
            }
            finally
            {
                File.Delete(tempLongPathFilename);
            }
        }
Exemple #22
0
        public void TestCopyWithOverwrite()
        {
            var destLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("filename (Copy).ext").ToString();

            File.Copy(longPathFilename, destLongPathFilename);

            try
            {
                Assert.IsTrue(File.Exists(destLongPathFilename));
                File.Copy(longPathFilename, destLongPathFilename, true);
                Assert.AreEqual(File.ReadAllText(longPathFilename), File.ReadAllText(destLongPathFilename));
            }
            finally
            {
                File.Delete(destLongPathFilename);
            }
        }
Exemple #23
0
        public void TestOpenReadWithWrite()
        {
            var tempLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("file31.ext").ToString();
            var fi = new FileInfo(tempLongPathFilename);

            try
            {
                using (var fileStream = fi.Open(FileMode.Append, FileAccess.Read))
                {
                    fileStream.WriteByte(43);
                }
            }
            finally
            {
                File.Delete(tempLongPathFilename);
            }
        }
Exemple #24
0
        public void TestCopyToWithoutOverwriteAndExistingFile()
        {
            var fi = new FileInfo(longPathFilename);
            var destLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("filename (Copy).ext").ToString();

            fi.CopyTo(destLongPathFilename);

            try
            {
                Assert.IsTrue(File.Exists(destLongPathFilename));
                fi.CopyTo(destLongPathFilename);
            }
            finally
            {
                File.Delete(destLongPathFilename);
            }
        }
 //Added size return, since symbolic links return 0, we use this function also to return the size of the file.
 private long CanAccessFile(string fileName)
 {
     try
     {
         using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
         {
             long size = fs.Seek(0, SeekOrigin.End);
             fs.Close();
             return(size);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(0);
     }
 }
Exemple #26
0
        public static void FixLibraryFolders()
        {
            var folders = Directory.EnumerateDirectories(Paths.OutputPath, "*", SearchOption.TopDirectoryOnly);

            foreach (var folder in folders)
            {
                var name    = Path.GetFileName(folder);
                var oldName = name;
                name = Regex.Replace(name, @"\b(HYBRID|DYNAMiCS|PROPER|VSTi|RTAS|CHAOS|AMPLiFY|AU|MATRiX|DVDR|WAV|AiR|ArCADE|VR|CDDA|PAD|MiDi|CoBaLT|DiSCOVER)\b", "");
                name = Regex.Replace(name, @"\b(WareZ Audio info|Kontakt|Audiostrike|SYNTHiC4TE|AUDIOXiMiK|MAGNETRiXX|TZ7iSO|KLI|DVDriSO|DVD9|KRock|ACiD|REX|RMX|SynthX|AiFF|Apple Loops|AiRISO|MULTiFORMAT|AudioP2P|GHOSTiSO|REX2|DXi|HYBRiD|AKAI|ALFiSO)\b", "", RegexOptions.IgnoreCase);
                name = Regex.Replace(name, @"  +", " ");
                if (name != oldName && !Directory.Exists(Path.GetDirectoryName(folder) + @"\" + name))
                {
                    File.Move(folder, Path.GetDirectoryName(folder) + @"\" + name);
                }
            }
        }
        private void DoNodesForFolder(string cat, string sub)
        {
            string currPath = path + cat + "\\" + sub + "\\";

            string[] fl = Directory.GetFiles(currPath, "*.*", SearchOption.AllDirectories)
                          .Where(s => s.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)).ToArray();
            foreach (string f in fl)
            {
                string nm = f.Substring(path.Length + 2 + cat.Length + sub.Length);
                nm = nm.Substring(0, nm.Length - 4);
                string   nameForFile  = f.Substring(0, f.Length - 4);
                string   txtFile      = nameForFile + ".txt";
                string   fullTextFile = nameForFile + " Full Text.txt";
                string[] contents;
                if (File.Exists(txtFile))
                {
                    contents = File.ReadLines(txtFile).ToArray();
                }
                else
                {
                    File.WriteAllText(txtFile, nm);
                    contents    = new string[1];
                    contents[0] = nm;
                }
                string ft = "";
                if (File.Exists(fullTextFile))
                {
                    string[] ftLines = File.ReadLines(fullTextFile).ToArray();
                    foreach (string s in ftLines)
                    {
                        ft += s + " ";
                    }
                    ft = ft.Trim();
                }
                List <string> goodTags = new List <string>();
                for (int i = 1; i < contents.Length; i++)
                {
                    if (contents[i] != "")
                    {
                        goodTags.Add(contents[i]);
                    }
                }
                files.Add(new DataFile(contents[0], goodTags.ToArray(), cat, sub, nm, ft));
            }
        }
Exemple #28
0
        public void TestLengthWithBadPath()
        {
            var filename = Util.CreateNewFile(longPathDirectory);

            Pri.LongPath.FileInfo fi;
            try
            {
                fi = new FileInfo(filename);
            }
            catch
            {
                File.Delete(filename);
                throw;
            }
            fi.Delete();
            fi.Refresh();
            var l = fi.Length;
        }
Exemple #29
0
            /// <summary>
            /// Transforms a file into its cryptographically strong equivalent using AES256 in CBC mode.
            /// </summary>
            /// <param name="originalFile">The path to the file to be cryptographically transformed.</param>
            /// <param name="encryptedFile">The path where the new file will be created.</param>
            /// <param name="password">The key to be used during the cryptographic transformation.</param>
            /// <returns>A flag determining whether or not the operation was successful.</returns>
            public static bool EncryptFile(string originalFile, string encryptedFile, byte[] password)
            {
                try
                {
                    string originalFilename  = originalFile;
                    string encryptedFilename = encryptedFile;

                    using (var originalStream = LongFile.Open(originalFile, FileMode.Open))
                        using (var encryptedStream = LongFile.Create(encryptedFile, 8192))
                            using (var encTransform = new EtM_EncryptTransform(key: password))
                                using (var crypoStream = new CryptoStream(encryptedStream, encTransform, CryptoStreamMode.Write))
                                {
                                    originalStream.CopyTo(crypoStream);
                                }
                    return(true);
                }
                catch { return(false); }
            }
Exemple #30
0
 public static bool IsDirectoryWritable(string dirPath, bool throwIfFails = false)
 {
     try
     {
         using (File.Create(Path.Combine(dirPath, Path.GetRandomFileName()), 1, FileOptions.DeleteOnClose))
         {
             return(true);
         }
     }
     catch
     {
         if (throwIfFails)
         {
             throw;
         }
         return(false);
     }
 }