예제 #1
0
        private void DumpReadAllLines(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
            var tmp      = Path.Combine(Path.GetTempPath(), "File.SetAttributes()-" + Path.GetRandomFileName());
            var tempPath = isLocal ? tmp : Path.LocalToUnc(tmp);

            // Create file and append text.
            var tempFile = Path.GetTempFileName();

            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(tempFile, createText);

            Console.WriteLine("\nFile.ReadAllLines()\n");
            var readText = File.ReadAllLines(tempFile);

            foreach (var s in readText)
            {
                Console.WriteLine("\t{0}", s);
                Assert.IsTrue(createText.Contains(s));
            }

            Console.WriteLine("\nFile.ReadLines()\n");
            foreach (var s in File.ReadLines((tempFile)))
            {
                Console.WriteLine("\t{0}", s);
                Assert.IsTrue(createText.Contains(s));
            }

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
        }
예제 #2
0
        static Utils()
        {
            if (!Directory.Exists(Consts.LocalAppDataPath))
            {
                Directory.CreateDirectory(Consts.LocalAppDataPath);
            }

            var programName = Assembly.GetEntryAssembly()?.Location ?? "Wabbajack";

            LogFile    = programName + ".log";
            _startTime = DateTime.Now;

            if (LogFile.FileExists())
            {
                File.Delete(LogFile);
            }

            var watcher = new FileSystemWatcher(Consts.LocalAppDataPath);

            AppLocalEvents = Observable.Merge(Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Changed += h, h => watcher.Changed -= h).Select(e => (FileEventType.Changed, e.EventArgs)),
                                              Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Created += h, h => watcher.Created -= h).Select(e => (FileEventType.Created, e.EventArgs)),
                                              Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Deleted += h, h => watcher.Deleted -= h).Select(e => (FileEventType.Deleted, e.EventArgs)))
                             .ObserveOn(RxApp.TaskpoolScheduler);
            watcher.EnableRaisingEvents = true;
        }
예제 #3
0
        private async Task DownloadMissingArchives(List <Archive> missing, bool download = true)
        {
            if (download)
            {
                foreach (var a in missing.Where(a => a.State.GetType() == typeof(ManualDownloader.State)))
                {
                    var outputPath = Path.Combine(DownloadFolder, a.Name);
                    await a.State.Download(a, outputPath);
                }
            }

            await missing.Where(a => a.State.GetType() != typeof(ManualDownloader.State))
            .PMap(Queue, async archive =>
            {
                Info($"Downloading {archive.Name}");
                var outputPath = Path.Combine(DownloadFolder, archive.Name);

                if (download)
                {
                    if (outputPath.FileExists())
                    {
                        File.Delete(outputPath);
                    }
                }

                return(await DownloadArchive(archive, download));
            });
        }
예제 #4
0
        private void DumpClassByHandleFileInfo(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
            var tempPath = Path.GetTempPath("File.GetFileInfoByHandle()-" + Path.GetRandomFileName());

            if (!isLocal)
            {
                tempPath = Path.LocalToUnc(tempPath);
            }

            Console.WriteLine("\nInput File Path: [{0}]", tempPath);

            var stream = File.Create(tempPath);

            stream.WriteByte(1);

            UnitTestConstants.StopWatcher(true);
            var bhfi = File.GetFileInfoByHandle(stream.SafeFileHandle);

            Console.WriteLine(UnitTestConstants.Reporter());

            Assert.IsTrue(UnitTestConstants.Dump(bhfi, -18));

            Assert.AreEqual(System.IO.File.GetCreationTimeUtc(tempPath), bhfi.CreationTimeUtc);
            Assert.AreEqual(System.IO.File.GetLastAccessTimeUtc(tempPath), bhfi.LastAccessTimeUtc);
            Assert.AreEqual(System.IO.File.GetLastWriteTimeUtc(tempPath), bhfi.LastWriteTimeUtc);

            stream.Close();

            File.Delete(tempPath, true);
            Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed.");
            Console.WriteLine();
        }
예제 #5
0
        public void File_WriteAllLines()
        {
            Console.WriteLine("File.WriteAllLines()");
            Console.WriteLine("\n Default AlphaFS Encoding: [{0}]", NativeMethods.DefaultFileEncoding.EncodingName);

            // Create file and append text.
            var tempFile = Path.GetTempFileName();

            var allLines = new[] { UnitTestConstants.TenNumbers, UnitTestConstants.TextHelloWorld, UnitTestConstants.TextGoodbyeWorld, UnitTestConstants.TextUnicode };

            // Create real UTF-8 file.
            File.WriteAllLines(tempFile, allLines, NativeMethods.DefaultFileEncoding);

            // Read filestream contents.
            using (var streamRead = File.OpenText(tempFile))
            {
                var line = streamRead.ReadToEnd();

                Console.WriteLine("\n Created: [{0}] filestream: [{1}]\n\n WriteAllLines content:\n{2}", streamRead.CurrentEncoding.EncodingName, tempFile, line);

                foreach (var line2 in allLines)
                {
                    Assert.IsTrue(line.Contains(line2));
                }
            }

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
        }
예제 #6
0
 private async Task InstallIncludedFiles()
 {
     Info("Writing inline files");
     await ModList.Directives
     .OfType <InlineFile>()
     .PMap(Queue, directive =>
     {
         Status($"Writing included file {directive.To}");
         var outPath = Path.Combine(OutputFolder, directive.To);
         if (File.Exists(outPath))
         {
             File.Delete(outPath);
         }
         if (directive is RemappedInlineFile)
         {
             WriteRemappedFile((RemappedInlineFile)directive);
         }
         else if (directive is CleanedESM)
         {
             GenerateCleanedESM((CleanedESM)directive);
         }
         else
         {
             File.WriteAllBytes(outPath, LoadBytesFromPath(directive.SourceDataID));
         }
     });
 }
예제 #7
0
        public async Task DownloadMissingArchives(List <Archive> missing, bool download = true)
        {
            if (download)
            {
                foreach (var a in missing.Where(a => a.State.GetType() == typeof(ManualDownloader.State)))
                {
                    var outputPath = Path.Combine(DownloadFolder, a.Name);
                    await a.State.Download(a, outputPath);
                }
            }

            await missing.Where(a => a.State.GetType() != typeof(ManualDownloader.State))
            .PMap(Queue, async archive =>
            {
                Info($"Downloading {archive.Name}");
                var outputPath = Path.Combine(DownloadFolder, archive.Name);

                if (download)
                {
                    if (outputPath.FileExists())
                    {
                        var orig_name  = Path.GetFileNameWithoutExtension(archive.Name);
                        var ext        = Path.GetExtension(archive.Name);
                        var unique_key = archive.State.PrimaryKeyString.StringSHA256Hex();
                        outputPath     = Path.Combine(DownloadFolder, orig_name + "_" + unique_key + "_" + ext);
                        if (outputPath.FileExists())
                        {
                            File.Delete(outputPath);
                        }
                    }
                }

                return(await DownloadArchive(archive, download, outputPath));
            });
        }
예제 #8
0
 /// <summary>
 /// Delete the temoporary file associated with this file
 /// </summary>
 internal void Unstage()
 {
     if (IsStaged && !IsConcrete)
     {
         File.Delete(_stagedPath);
         _stagedPath = null;
     }
 }
예제 #9
0
        public async Task <IActionResult> DeleteUpdates()
        {
            var lists = await SQL.GetDetailedModlistStatuses();

            var archives = lists.SelectMany(list => list.Archives)
                           .Select(a => a.Archive.Hash.ToHex())
                           .ToHashSet();

            var toDelete = new List <string>();
            var toSave   = new List <string>();

            using (var client = new FtpClient("storage.bunnycdn.com"))
            {
                client.Credentials = new NetworkCredential(_settings.BunnyCDN_User, _settings.BunnyCDN_Password);
                await client.ConnectAsync();

                foreach (var file in Directory.GetFiles("updates"))
                {
                    var relativeName = Path.GetFileName(file);
                    var parts        = Path.GetFileName(file).Split('_', StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length != 2)
                    {
                        continue;
                    }

                    if (parts[0] == parts[1])
                    {
                        toDelete.Add(relativeName);
                        continue;
                    }

                    if (!archives.Contains(parts[0]))
                    {
                        toDelete.Add(relativeName);
                    }
                    else
                    {
                        toSave.Add(relativeName);
                    }
                }

                foreach (var delete in toDelete)
                {
                    Utils.Log($"Deleting update {delete}");
                    if (await client.FileExistsAsync($"updates/{delete}"))
                    {
                        await client.DeleteFileAsync($"updates/{delete}");
                    }
                    if (AlphaFile.Exists($"updates\\{delete}"))
                    {
                        AlphaFile.Delete($"updates\\{delete}");
                    }
                }
            }

            return(Ok(new { Save = toSave.ToArray(), Delete = toDelete.ToArray() }.ToJson()));
        }
예제 #10
0
        private void DumpReadWriteAllBytes(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
            var tempPath = Path.GetTempPath("File.ReadWriteAllBytes()-" + Path.GetRandomFileName());

            if (!isLocal)
            {
                tempPath = Path.LocalToUnc(tempPath);
            }

            var size  = 10000;
            var text  = Encoding.UTF8.GetBytes(new string('X', size));
            var allOk = true;

            try
            {
                File.WriteAllBytes(tempPath, text);
                Console.WriteLine("\nWriteAllBytes(): [{0}] bytes: [{1}]", size, tempPath);
            }
            catch (Exception ex)
            {
                allOk = false;
                Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            Assert.IsTrue(File.Exists(tempPath), "File.WriteAllBytes(): File was not created.");
            var fileSize = File.GetSize(tempPath);

            Assert.AreEqual(size, fileSize);
            Assert.IsTrue(allOk);



            byte[] readAllAlphaFS = { };
            byte[] readAllSysIo   = { };

            try
            {
                readAllAlphaFS = File.ReadAllBytes(tempPath);
                readAllSysIo   = System.IO.File.ReadAllBytes(tempPath);
                Console.WriteLine("\nReadAllBytes(): [{0}] bytes.", readAllAlphaFS.Length);
            }
            catch (Exception ex)
            {
                allOk = false;
                Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }

            Assert.AreEqual(readAllAlphaFS.Length, fileSize, "File.ReadAllBytes(): Number of bytes are different.");
            Assert.AreEqual(readAllAlphaFS.Length, readAllSysIo.Length, "File.ReadAllBytes(): AlphaFS != System.IO");



            File.Delete(tempPath, true);
            Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed.");
            Assert.IsTrue(allOk);
            Console.WriteLine("\n");
        }
예제 #11
0
        /// <summary>
        /// The user may already have some files in the OutputFolder. If so we can go through these and
        /// figure out which need to be updated, deleted, or left alone
        /// </summary>
        public async Task OptimizeModlist()
        {
            Utils.Log("Optimizing Modlist directives");
            var indexed = ModList.Directives.ToDictionary(d => d.To);

            UpdateTracker.NextStep("Looking for files to delete");
            await Directory.EnumerateFiles(OutputFolder, "*", DirectoryEnumerationOptions.Recursive)
            .PMap(Queue, UpdateTracker, f =>
            {
                var relative_to = f.RelativeTo(OutputFolder);
                Utils.Status($"Checking if modlist file {relative_to}");
                if (indexed.ContainsKey(relative_to) || f.IsInPath(DownloadFolder))
                {
                    return;
                }

                Utils.Log($"Deleting {relative_to} it's not part of this modlist");
                File.Delete(f);
            });

            UpdateTracker.NextStep("Looking for unmodified files");
            (await indexed.Values.PMap(Queue, UpdateTracker, d =>
            {
                // Bit backwards, but we want to return null for
                // all files we *want* installed. We return the files
                // to remove from the install list.
                Status($"Optimizing {d.To}");
                var path = Path.Combine(OutputFolder, d.To);
                if (!File.Exists(path))
                {
                    return(null);
                }

                var fi = new FileInfo(path);
                if (fi.Length != d.Size)
                {
                    return(null);
                }

                return(path.FileHash() == d.Hash ? d : null);
            }))
            .Where(d => d != null)
            .Do(d => indexed.Remove(d.To));

            UpdateTracker.NextStep("Updating Modlist");
            Utils.Log($"Optimized {ModList.Directives.Count} directives to {indexed.Count} required");
            var requiredArchives = indexed.Values.OfType <FromArchive>()
                                   .GroupBy(d => d.ArchiveHashPath[0])
                                   .Select(d => d.Key)
                                   .ToHashSet();

            ModList.Archives   = ModList.Archives.Where(a => requiredArchives.Contains(a.Hash)).ToList();
            ModList.Directives = indexed.Values.ToList();
        }
예제 #12
0
 public static void ToJSON <T>(this T obj, string filename)
 {
     if (File.Exists(filename))
     {
         File.Delete(filename);
     }
     File.WriteAllText(filename,
                       JsonConvert.SerializeObject(obj, Formatting.Indented,
                                                   new JsonSerializerSettings {
         TypeNameHandling = TypeNameHandling.Auto
     }));
 }
예제 #13
0
        static Utils()
        {
            var programName = Assembly.GetEntryAssembly()?.Location ?? "Wabbajack";

            LogFile    = programName + ".log";
            _startTime = DateTime.Now;

            if (LogFile.FileExists())
            {
                File.Delete(LogFile);
            }
        }
예제 #14
0
 private async Task InstallIncludedDownloadMetas()
 {
     await ModList.Directives
     .OfType <ArchiveMeta>()
     .PMap(Queue, directive =>
     {
         Status($"Writing included .meta file {directive.To}");
         var outPath = Path.Combine(DownloadFolder, directive.To);
         if (File.Exists(outPath))
         {
             File.Delete(outPath);
         }
         File.WriteAllBytes(outPath, LoadBytesFromPath(directive.SourceDataID));
     });
 }
예제 #15
0
        public void File_AppendAllLinesThenReadAllLinesShouldReturnSameCollection()
        {
            var file   = Path.GetTempFileName();
            var sample = new [] { "line one", "line two" };

            try
            {
                File.AppendAllLines(file, sample);
                CollectionAssert.AreEquivalent(sample, File.ReadAllLines(file).ToArray());
            }
            finally
            {
                File.Delete(file);
            }
        }
예제 #16
0
        public async ValueTask DisposeAsync()
        {
            var exts = new[] { ".md", ".exe" };
            await WorkingDirectory.Combine(ID).DeleteDirectory();

            Profiles.Do(p =>
            {
                foreach (var ext in exts)
                {
                    var path = Path.Combine(Directory.GetCurrentDirectory(), p + ext);
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
            });
        }
예제 #17
0
        public void Dispose()
        {
            var exts = new [] { ".md", ".exe" };

            Utils.DeleteDirectory(Path.Combine(WorkingDirectory, ID));
            Profiles.Do(p =>
            {
                foreach (var ext in exts)
                {
                    var path = Path.Combine(Directory.GetCurrentDirectory(), p + ext);
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
            });
        }
예제 #18
0
        public void File_ReadAllText()
        {
            Console.WriteLine("File.ReadAllText()\n");

            // Create file and append text.
            var tempFile = Path.GetTempFileName();

            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(tempFile, createText);

            // Open the file to read from.
            var textRead = File.ReadAllText(tempFile);

            Console.WriteLine(textRead);

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
        }
예제 #19
0
        public void File_WriteAllText()
        {
            Console.WriteLine("File.WriteAllText()");
            Console.WriteLine("\n\tDefault AlphaFS Encoding: [{0}]", NativeMethods.DefaultFileEncoding.EncodingName);

            // Create file and append text.
            var tempFile = Path.GetTempFileName();

            var allLines = UnitTestConstants.TextHelloWorld;

            // Create real UTF-8 file.
            File.WriteAllText(tempFile, allLines, NativeMethods.DefaultFileEncoding);

            // Read filestream contents.
            using (var streamRead = File.OpenText(tempFile))
            {
                var line = streamRead.ReadToEnd();

                Console.WriteLine("\n\tCreated: [{0}] filestream: [{1}]\n\n\tWriteAllText content:\n{2}", streamRead.CurrentEncoding.EncodingName, tempFile, line);

                Assert.IsTrue(line.Contains(allLines));
            }

            // (over)Write.
            File.WriteAllText(tempFile, "Append 1");
            File.WriteAllText(tempFile, allLines);
            File.WriteAllText(tempFile, "Append 2");
            File.WriteAllText(tempFile, allLines);

            // Read filestream contents.
            using (var streamRead = File.OpenText(tempFile))
            {
                var line = streamRead.ReadToEnd();

                Console.WriteLine("\tWriteAllText content:\n{0}", line);

                Assert.IsTrue(line.Contains(allLines));
                Assert.IsTrue(!line.Contains("Append 1"));
                Assert.IsTrue(!line.Contains("Append 2"));
            }

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
        }
예제 #20
0
        public static void Rotate(string filenameBase)
        {
            if (File.Exists(filenameBase))
            {
                for (int i = 8; i >= 0; i--)
                {
                    string fn = filenameBase + "." + i;
                    if (File.Exists(fn))
                    {
                        string fn2 = filenameBase + "." + (i + 1);
                        if (File.Exists(fn2))
                        {
                            File.Delete(fn2);
                        }
                        File.Move(fn, fn2);
                    }
                }

                File.Copy(filenameBase, filenameBase + ".0");
            }
        }
예제 #21
0
        public void SyncToDisk()
        {
            if (!_disableDiskCache)
            {
                Utils.Status("Syncing VFS Cache");
                lock (this)
                {
                    try
                    {
                        _isSyncing = true;

                        if (File.Exists("vfs_cache.bin_new"))
                        {
                            File.Delete("vfs_cache.bin_new");
                        }

                        using (var fs = File.OpenWrite("vfs_cache.bin_new"))
                            using (var bw = new BinaryWriter(fs))
                            {
                                Utils.Log($"Syncing VFS to Disk: {_files.Count} entries");
                                foreach (var f in _files.Values)
                                {
                                    f.Write(bw);
                                }
                            }

                        if (File.Exists("vfs_cache.bin"))
                        {
                            File.Delete("vfs_cache.bin");
                        }

                        File.Move("vfs_cache.bin_new", "vfs_cache.bin");
                    }
                    finally
                    {
                        _isSyncing = false;
                    }
                }
            }
        }
예제 #22
0
파일: AlphaFSToys.cs 프로젝트: CDEApp/CDE
        public void GetFilesWithExtension_FileContainingPatternUseToReturn()
        {
            const string name1 = "G-SN750B_02_S13UJ1NQ221583.cde";
            const string name2 = "G-SN750B_02_S13UJ1NQ221583.cde-backup-with-hash";
            var          f1    = File.Create(name1);
            var          f2    = File.Create(name2);

            f1.Close();
            f2.Close();
            var files = AlphaFSHelper.GetFilesWithExtension(".", "cde");

            foreach (var file in files)
            {
                Console.WriteLine($"file {file}");
            }

            //System.Threading.Thread.Sleep(1000); // delay 1 second

            File.Delete(name1);
            File.Delete(name2);

            Assert.That(files.Count(), Is.EqualTo(1), "Oops somehow we got a file not ending in \"cde\" in our result set.");
        }
예제 #23
0
        private void LoadFromDisk()
        {
            try
            {
                Utils.Log("Loading VFS Cache");
                if (!File.Exists("vfs_cache.bin"))
                {
                    return;
                }
                _files = new Dictionary <string, VirtualFile>();

                try
                {
                    using (var fs = File.OpenRead("vfs_cache.bin"))
                        using (var br = new BinaryReader(fs))
                        {
                            while (true)
                            {
                                var fr = VirtualFile.Read(br);
                                _files.Add(fr.FullPath, fr);
                            }
                        }
                }
                catch (EndOfStreamException ex)
                {
                }


                CleanDB();
            }
            catch (Exception ex)
            {
                Utils.Log($"Purging cache due to {ex}");
                File.Delete("vfs_cache.bson");
                _files.Clear();
            }
        }
예제 #24
0
        private static void DeleteDirectory(string path)
        {
            Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
            .DoProgress("Cleaning VFS Files", file =>
            {
                try
                {
                    var fi         = new FileInfo(file);
                    fi.Attributes &= ~FileAttributes.ReadOnly;
                    File.Delete(file);
                }
                catch (Exception ex)
                {
                    Utils.Log(ex.ToString());
                }
            });

            Directory.EnumerateDirectories(path, DirectoryEnumerationOptions.Recursive)
            .OrderByDescending(d => d.Length)
            .DoProgress("Cleaning VFS Folders", folder =>
            {
                try
                {
                    if (!Directory.Exists(folder))
                    {
                        return;
                    }
                    var di         = new DirectoryInfo(folder);
                    di.Attributes &= ~FileAttributes.ReadOnly;
                    Directory.Delete(path, true);
                }
                catch (Exception ex)
                {
                    Utils.Log(ex.ToString());
                }
            });
        }
예제 #25
0
        public void File_Encrypt()
        {
            Console.WriteLine("File.Encrypt()");

            // Create file and append text.
            var tempFile = Path.GetTempFileName();

            // Append text as UTF-8, default.
            File.AppendAllText(tempFile, UnitTestConstants.TextHelloWorld);

            var utf8             = NativeMethods.DefaultFileEncoding.BodyName.ToUpperInvariant();
            var readText8        = File.ReadAllText(tempFile);
            var actual           = File.GetAttributes(tempFile);
            var encryptionStatus = File.GetEncryptionStatus(tempFile);

            Console.WriteLine("\n\tCreated {0} file: [{1}]", utf8, tempFile);
            Console.WriteLine("\tContent: [{0}]", readText8);
            Console.WriteLine("\n\tFile.GetAttributes(): [{0}]", actual);
            Console.WriteLine("\tEncryption status   : [{0}]", encryptionStatus);

            var encryptOk = false;

            try
            {
                File.Encrypt(tempFile);
                encryptOk = true;
                actual    = File.GetAttributes(tempFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            encryptionStatus = File.GetEncryptionStatus(tempFile);
            Console.WriteLine("\n\tFile.Encrypt() (Should be True): [{0}]", encryptOk);
            Console.WriteLine("\tFile.GetAttributes()           : [{0}]", actual);
            Console.WriteLine("\tEncryption status              : [{0}]", encryptionStatus);

            var decryptOk = false;

            try
            {
                File.Decrypt(tempFile);
                decryptOk = true;
                actual    = File.GetAttributes(tempFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            var decryptionStatus = File.GetEncryptionStatus(tempFile);

            Console.WriteLine("\n\tFile.Decrypt() (Should be True): [{0}]:", decryptOk);
            Console.WriteLine("\tFile.GetAttributes()           : [{0}]", actual);
            Console.WriteLine("\tDecryption status              : [{0}]", decryptionStatus);

            Assert.IsTrue(encryptOk, "File should be encrypted.");
            Assert.IsTrue(encryptionStatus == FileEncryptionStatus.Encrypted, "File should be encrypted.");
            Assert.IsTrue(decryptOk, "File should be decrypted.");
            Assert.IsTrue(decryptionStatus == FileEncryptionStatus.Encryptable, "File should be decrypted.");

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
        }
예제 #26
0
파일: PathTest.cs 프로젝트: jdstroy/AlphaFS
        // Pattern: <class>_<function>_<scenario>_<expected result>

        #region Unit Tests

        private void Dump83Path(bool isLocal)
        {
            #region Setup

            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);

            var myLongPath = Path.GetTempPath("My Long Data File Or Directory");
            if (!isLocal)
            {
                myLongPath = Path.LocalToUnc(myLongPath);
            }

            Console.WriteLine("\nInput Path: [{0}]\n", myLongPath);

            #endregion // Setup

            #region File

            string short83Path;

            try
            {
                using (File.Create(myLongPath))

                    UnitTestConstants.StopWatcher(true);

                short83Path = Path.GetShort83Path(myLongPath);

                Console.WriteLine("Short 8.3 file path    : [{0}]\t\t\t{1}", short83Path, UnitTestConstants.Reporter(true));

                Assert.IsTrue(!short83Path.Equals(myLongPath));

                Assert.IsTrue(short83Path.EndsWith(@"~1"));



                UnitTestConstants.StopWatcher(true);

                var longFrom83Path = Path.GetLongFrom83ShortPath(short83Path);

                Console.WriteLine("Long path from 8.3 path: [{0}]{1}", longFrom83Path, UnitTestConstants.Reporter(true));

                Assert.IsTrue(longFrom83Path.Equals(myLongPath));

                Assert.IsFalse(longFrom83Path.EndsWith(@"~1"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            finally
            {
                if (File.Exists(myLongPath))
                {
                    File.Delete(myLongPath);
                }
            }
            Console.WriteLine();

            #endregion // File

            #region Directory

            try
            {
                Directory.CreateDirectory(myLongPath);

                UnitTestConstants.StopWatcher(true);

                short83Path = Path.GetShort83Path(myLongPath);

                Console.WriteLine("Short 8.3 directory path: [{0}]\t\t\t{1}", short83Path, UnitTestConstants.Reporter(true));

                Assert.IsFalse(short83Path.Equals(myLongPath));

                Assert.IsTrue(short83Path.EndsWith(@"~1"));



                UnitTestConstants.StopWatcher(true);

                var longFrom83Path = Path.GetLongFrom83ShortPath(short83Path);

                Console.WriteLine("Long path from 8.3 path : [{0}]{1}", longFrom83Path, UnitTestConstants.Reporter(true));

                Assert.IsTrue(longFrom83Path.Equals(myLongPath));

                Assert.IsFalse(longFrom83Path.EndsWith(@"~1"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
            }
            finally
            {
                if (Directory.Exists(myLongPath))
                {
                    Directory.Delete(myLongPath);
                }
            }
            Console.WriteLine();

            #endregion // Directory
        }
예제 #27
0
파일: PathTest.cs 프로젝트: jdstroy/AlphaFS
        private void DumpGetFinalPathNameByHandle(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);

            var tempFile = Path.GetTempFileName();

            if (!isLocal)
            {
                tempFile = Path.LocalToUnc(tempFile);
            }

            var  longTempStream = Path.LongPathPrefix + tempFile;
            bool gotFileNameNormalized;
            bool gotFileNameOpened;
            bool gotVolumeNameDos;
            bool gotVolumeNameGuid;
            bool gotVolumeNameNt;
            bool gotVolumeNameNone;
            bool gotSomething;

            using (var stream = File.Create(tempFile))
            {
                // For Windows versions < Vista, the file must be > 0 bytes.
                if (!NativeMethods.IsAtLeastWindowsVista)
                {
                    stream.WriteByte(1);
                }

                var handle = stream.SafeFileHandle;

                UnitTestConstants.StopWatcher(true);
                var fileNameNormalized = Path.GetFinalPathNameByHandle(handle);
                var fileNameOpened     = Path.GetFinalPathNameByHandle(handle, FinalPathFormats.FileNameOpened);

                var volumeNameDos  = Path.GetFinalPathNameByHandle(handle, FinalPathFormats.None);
                var volumeNameGuid = Path.GetFinalPathNameByHandle(handle, FinalPathFormats.VolumeNameGuid);
                var volumeNameNt   = Path.GetFinalPathNameByHandle(handle, FinalPathFormats.VolumeNameNT);
                var volumeNameNone = Path.GetFinalPathNameByHandle(handle, FinalPathFormats.VolumeNameNone);

                // These three output the same.
                gotFileNameNormalized = !string.IsNullOrWhiteSpace(fileNameNormalized) && longTempStream.Equals(fileNameNormalized);
                gotFileNameOpened     = !string.IsNullOrWhiteSpace(fileNameOpened) && longTempStream.Equals(fileNameOpened);
                gotVolumeNameDos      = !string.IsNullOrWhiteSpace(volumeNameDos) && longTempStream.Equals(volumeNameDos);

                gotVolumeNameGuid = !string.IsNullOrWhiteSpace(volumeNameGuid) && volumeNameGuid.StartsWith(Path.VolumePrefix) && volumeNameGuid.EndsWith(volumeNameNone);
                gotVolumeNameNt   = !string.IsNullOrWhiteSpace(volumeNameNt) && volumeNameNt.StartsWith(Path.DevicePrefix);
                gotVolumeNameNone = !string.IsNullOrWhiteSpace(volumeNameNone) && tempFile.EndsWith(volumeNameNone);

                Console.WriteLine("\nInput Path: [{0}]", tempFile);
                Console.WriteLine("\n\tFilestream.Name  : [{0}]", stream.Name);
                Console.WriteLine("\tFilestream.Length: [{0}] (Note: For Windows versions < Vista, the file must be > 0 bytes.)\n", Utils.UnitSizeToText(stream.Length));

                Console.WriteLine("\tFinalPathFormats.None          : [{0}]", fileNameNormalized);
                Console.WriteLine("\tFinalPathFormats.FileNameOpened: [{0}]", fileNameOpened);
                Console.WriteLine("\tFinalPathFormats.VolumeNameDos : [{0}]", volumeNameDos);
                Console.WriteLine("\tFinalPathFormats.VolumeNameGuid: [{0}]", volumeNameGuid);
                Console.WriteLine("\tFinalPathFormats.VolumeNameNT  : [{0}]", volumeNameNt);
                Console.WriteLine("\tFinalPathFormats.VolumeNameNone: [{0}]", volumeNameNone);

                Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true));

                gotSomething = true;
            }


            var fileExists = File.Exists(tempFile);

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");

            Assert.IsTrue(fileExists);
            Assert.IsTrue(gotFileNameNormalized);
            Assert.IsTrue(gotFileNameOpened);
            Assert.IsTrue(gotVolumeNameDos);
            Assert.IsTrue(gotVolumeNameGuid);
            Assert.IsTrue(gotVolumeNameNt);
            Assert.IsTrue(gotVolumeNameNone);
            Assert.IsTrue(gotSomething);



            // AlphaFS implementation of fileStream.Name returns = "[Unknown]"
            // System.IO returns the full path.
            Console.WriteLine();
            var fileName = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%") + "foo.bar");

            var fileStream2 = System.IO.File.Create(fileName);

            Assert.AreEqual(fileStream2.Name, fileName);
            fileStream2.Close();
            File.Delete(fileName);

            var fileStream     = File.Create(fileName);
            var fileStreamName = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(fileStream.SafeFileHandle);

            Assert.AreNotEqual(fileName, fileStream.Name);
            Assert.AreEqual(fileName, Path.GetRegularPath(fileStreamName));

            fileStream.Close();
            File.Delete(fileName);
        }
예제 #28
0
        public void File_AppendText()
        {
            Console.WriteLine("File.AppendText()");

            var    utf8 = NativeMethods.DefaultFileEncoding.BodyName.ToUpperInvariant();
            string line;
            var    matchLine = string.Empty;
            var    tempFile  = Path.GetTempFileName();

            StreamReader streamRead;
            StreamWriter streamWrite;

            Console.WriteLine("Default AlphaFS Encoding: {0}", NativeMethods.DefaultFileEncoding.EncodingName);

            #region Create Filestream, CreateText()

            // Create filestream and append text as UTF-8, default.
            using (streamWrite = File.CreateText(tempFile))
            {
                streamWrite.Write(UnitTestConstants.TextHelloWorld);
            }

            // Read filestream contents.
            using (streamRead = File.OpenText(tempFile))
            {
                while ((line = streamRead.ReadLine()) != null)
                {
                    Console.WriteLine("\n CreateText(): [{0}] filestream: [{1}]\n  Appended: [{2}]\n  Content : [{3}]", streamRead.CurrentEncoding.EncodingName, tempFile, UnitTestConstants.TextHelloWorld, line);
                    matchLine = line; // Catch the last line.
                }
            }
            Assert.IsTrue(matchLine.Equals(UnitTestConstants.TextHelloWorld, StringComparison.OrdinalIgnoreCase));

            #endregion // Create Filestream, CreateText()

            #region AppendText() to Filestream

            // Append text as UTF-8, default.
            using (streamWrite = File.AppendText(tempFile))
            {
                streamWrite.Write(UnitTestConstants.TextGoodbyeWorld);
            }

            // Read filestream contents.
            using (streamRead = File.OpenText(tempFile))
            {
                while ((line = streamRead.ReadLine()) != null)
                {
                    Console.WriteLine("\n AppendText() as [{0}]\n  Appended: [{1}]\n  Content : [{2}]", utf8, UnitTestConstants.TextGoodbyeWorld, line);
                }
            }

            // Append text as UTF-8, default.
            using (streamWrite = File.AppendText(tempFile))
            {
                streamWrite.WriteLine(UnitTestConstants.TextUnicode);
            }

            // Read filestream contents.
            matchLine = string.Empty;
            using (streamRead = File.OpenText(tempFile))
            {
                while ((line = streamRead.ReadLine()) != null)
                {
                    Console.WriteLine("\n AppendText() as [{0}]\n  Appended: [{1}]\n  Content : [{2}]", utf8, UnitTestConstants.TextGoodbyeWorld, line);
                    matchLine = line; // Catch the last line.
                }
            }

            Assert.IsTrue(matchLine.Equals(UnitTestConstants.TextHelloWorld + UnitTestConstants.TextGoodbyeWorld + UnitTestConstants.TextUnicode, StringComparison.OrdinalIgnoreCase));

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");

            #endregion // AppendText() to Filestream
        }
예제 #29
0
        protected override async Task <ExitCode> Run()
        {
            var modListPath = (AbsolutePath)Modlist;

            if (modListPath.Extension != Consts.ModListExtension && modListPath.FileName != (RelativePath)"modlist.txt")
            {
                return(CLIUtils.Exit($"The file {Modlist} is not a valid modlist file!", ExitCode.BadArguments));
            }

            if (Copy && Move)
            {
                return(CLIUtils.Exit("You can't set both copy and move flags!", ExitCode.BadArguments));
            }

            var isModlist = modListPath.Extension == Consts.ModListExtension;

            var list = new List <TransferFile>();

            if (isModlist)
            {
                ModList modlist;

                try
                {
                    modlist = AInstaller.LoadFromFile(modListPath);
                }
                catch (Exception e)
                {
                    return(CLIUtils.Exit($"Error while loading the Modlist!\n{e}", ExitCode.Error));
                }

                if (modlist == null)
                {
                    return(CLIUtils.Exit("The Modlist could not be loaded!", ExitCode.Error));
                }

                CLIUtils.Log($"Modlist contains {modlist.Archives.Count} archives.");

                modlist.Archives.Do(a =>
                {
                    var inputPath  = Path.Combine(Input, a.Name);
                    var outputPath = Path.Combine(Output, a.Name);

                    if (!File.Exists(inputPath))
                    {
                        CLIUtils.Log($"File {inputPath} does not exist, skipping.");
                        return;
                    }

                    CLIUtils.Log($"Adding {inputPath} to the transfer list.");
                    list.Add(new TransferFile(inputPath, outputPath));

                    var metaInputPath  = Path.Combine(inputPath, ".meta");
                    var metaOutputPath = Path.Combine(outputPath, ".meta");

                    if (File.Exists(metaInputPath))
                    {
                        CLIUtils.Log($"Found meta file {metaInputPath}");
                        if (IncludeMeta)
                        {
                            CLIUtils.Log($"Adding {metaInputPath} to the transfer list.");
                            list.Add(new TransferFile(metaInputPath, metaOutputPath));
                        }
                        else
                        {
                            CLIUtils.Log($"Meta file {metaInputPath} will be ignored.");
                        }
                    }
                    else
                    {
                        CLIUtils.Log($"Found no meta file for {inputPath}");
                        if (IncludeMeta)
                        {
                            if (string.IsNullOrWhiteSpace(a.Meta))
                            {
                                CLIUtils.Log($"Meta for {a.Name} is empty, this should not be possible but whatever.");
                                return;
                            }

                            CLIUtils.Log("Adding meta from archive info the transfer list");
                            list.Add(new TransferFile(a.Meta, metaOutputPath, true));
                        }
                        else
                        {
                            CLIUtils.Log($"Meta will be ignored for {a.Name}");
                        }
                    }
                });
            }
            else
            {
                if (!Directory.Exists(Mods))
                {
                    return(CLIUtils.Exit($"Mods directory {Mods} does not exist!", ExitCode.BadArguments));
                }

                CLIUtils.Log($"Reading modlist.txt from {Modlist}");
                string[] modlist = File.ReadAllLines(Modlist);

                if (modlist == null || modlist.Length == 0)
                {
                    return(CLIUtils.Exit($"Provided modlist.txt file at {Modlist} is empty or could not be read!", ExitCode.BadArguments));
                }

                var mods = modlist.Where(s => s.StartsWith("+")).Select(s => s.Substring(1)).ToHashSet();

                if (mods.Count == 0)
                {
                    return(CLIUtils.Exit("Counted mods from modlist.txt are 0!", ExitCode.BadArguments));
                }

                CLIUtils.Log($"Found {mods.Count} mods in modlist.txt");

                var downloads = new HashSet <string>();

                Directory.EnumerateDirectories(Mods, "*", SearchOption.TopDirectoryOnly)
                .Where(d => mods.Contains(Path.GetRelativePath(Path.GetDirectoryName(d), d)))
                .Do(d =>
                {
                    var meta = Path.Combine(d, "meta.ini");
                    if (!File.Exists(meta))
                    {
                        CLIUtils.Log($"Mod meta file {meta} does not exist, skipping");
                        return;
                    }

                    string[] ini = File.ReadAllLines(meta);
                    if (ini == null || ini.Length == 0)
                    {
                        CLIUtils.Log($"Mod meta file {meta} could not be read or is empty!");
                        return;
                    }

                    ini.Where(i => !string.IsNullOrWhiteSpace(i) && i.StartsWith("installationFile="))
                    .Select(i => i.Replace("installationFile=", ""))
                    .Do(i =>
                    {
                        CLIUtils.Log($"Found installationFile {i}");
                        downloads.Add(i);
                    });
                });

                CLIUtils.Log($"Found {downloads.Count} installationFiles from mod metas.");

                Directory.EnumerateFiles(Input, "*", SearchOption.TopDirectoryOnly)
                .Where(f => downloads.Contains(Path.GetFileNameWithoutExtension(f)))
                .Do(f =>
                {
                    CLIUtils.Log($"Found archive {f}");

                    var outputPath = Path.Combine(Output, Path.GetFileName(f));

                    CLIUtils.Log($"Adding {f} to the transfer list");
                    list.Add(new TransferFile(f, outputPath));

                    var metaInputPath = Path.Combine(f, ".meta");
                    if (File.Exists(metaInputPath))
                    {
                        CLIUtils.Log($"Found meta file for {f} at {metaInputPath}");
                        if (IncludeMeta)
                        {
                            var metaOutputPath = Path.Combine(outputPath, ".meta");
                            CLIUtils.Log($"Adding {metaInputPath} to the transfer list.");
                            list.Add(new TransferFile(metaInputPath, metaOutputPath));
                        }
                        else
                        {
                            CLIUtils.Log("Meta file will be ignored");
                        }
                    }
                    else
                    {
                        CLIUtils.Log($"Found no meta file for {f}");
                    }
                });
            }

            CLIUtils.Log($"Transfer list contains {list.Count} items");
            var success = 0;
            var failed  = 0;
            var skipped = 0;

            list.Do(f =>
            {
                if (File.Exists(f.Output))
                {
                    if (Overwrite)
                    {
                        CLIUtils.Log($"Output file {f.Output} already exists, it will be overwritten");
                        if (f.IsMeta || Move)
                        {
                            CLIUtils.Log($"Deleting file at {f.Output}");
                            try
                            {
                                File.Delete(f.Output);
                            }
                            catch (Exception e)
                            {
                                CLIUtils.Log($"Could not delete file {f.Output}!\n{e}");
                                failed++;
                            }
                        }
                    }
                    else
                    {
                        CLIUtils.Log($"Output file {f.Output} already exists, skipping");
                        skipped++;
                        return;
                    }
                }

                if (f.IsMeta)
                {
                    CLIUtils.Log($"Writing meta data to {f.Output}");
                    try
                    {
                        File.WriteAllText(f.Output, f.Input, Encoding.UTF8);
                        success++;
                    }
                    catch (Exception e)
                    {
                        CLIUtils.Log($"Error while writing meta data to {f.Output}!\n{e}");
                        failed++;
                    }
                }
                else
                {
                    if (Copy)
                    {
                        CLIUtils.Log($"Copying file {f.Input} to {f.Output}");
                        try
                        {
                            File.Copy(f.Input, f.Output, Overwrite ? CopyOptions.None : CopyOptions.FailIfExists, CopyMoveProgressHandler, null);
                            success++;
                        }
                        catch (Exception e)
                        {
                            CLIUtils.Log($"Error while copying file {f.Input} to {f.Output}!\n{e}");
                            failed++;
                        }
                    }
                    else if (Move)
                    {
                        CLIUtils.Log($"Moving file {f.Input} to {f.Output}");
                        try
                        {
                            File.Move(f.Input, f.Output, Overwrite ? MoveOptions.ReplaceExisting : MoveOptions.None, CopyMoveProgressHandler, null);
                            success++;
                        }
                        catch (Exception e)
                        {
                            CLIUtils.Log($"Error while moving file {f.Input} to {f.Output}!\n{e}");
                            failed++;
                        }
                    }
                }
            });

            CLIUtils.Log($"Skipped transfers: {skipped}");
            CLIUtils.Log($"Failed transfers: {failed}");
            CLIUtils.Log($"Successful transfers: {success}");

            return(0);
        }
예제 #30
0
        private void DumpAppendAllLines(bool isLocal)
        {
            #region Setup

            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
            var tempFolder = Path.GetTempPath();
            var tempPath   = Path.Combine(tempFolder, "File.Delete-" + Path.GetRandomFileName());
            if (!isLocal)
            {
                tempPath = Path.LocalToUnc(tempPath);
            }

            // Create file and append text.
            var tempFile = Path.GetTempFileName();
            if (!isLocal)
            {
                tempFile = Path.LocalToUnc(tempFile);
            }

            IEnumerable <string> allLines = new[] { UnitTestConstants.TenNumbers, UnitTestConstants.TextHelloWorld, UnitTestConstants.TextGoodbyeWorld, UnitTestConstants.TextUnicode };

            #endregion // Setup

            try
            {
                #region AppendAllLines

                Console.WriteLine("\nDefault AlphaFS Encoding: [{0}]", NativeMethods.DefaultFileEncoding.EncodingName);

                // Create real UTF-8 file.
                File.AppendAllLines(tempFile, allLines, NativeMethods.DefaultFileEncoding);

                // Read filestream contents.
                using (var streamRead = File.OpenText(tempFile))
                {
                    var line = streamRead.ReadToEnd();

                    Console.WriteLine("\nCreated: [{0}] filestream: [{1}]\n\n\tAppendAllLines content:\n{2}", streamRead.CurrentEncoding.EncodingName, tempFile, line);

                    foreach (var line2 in allLines)
                    {
                        Assert.IsTrue(line.Contains(line2));
                    }
                }

                // Append
                File.AppendAllLines(tempFile, new[] { "Append 1" });
                File.AppendAllLines(tempFile, allLines);
                File.AppendAllLines(tempFile, new[] { "Append 2" });
                File.AppendAllLines(tempFile, allLines);

                // Read filestream contents.
                using (var streamRead = File.OpenText(tempFile))
                {
                    var line = streamRead.ReadToEnd();

                    Console.WriteLine("AppendAllLines content:\n{0}", line);

                    foreach (var line2 in allLines)
                    {
                        Assert.IsTrue(line.Contains(line2));
                    }
                }

                #endregion // AppendAllLines
            }
            finally
            {
                File.Delete(tempFile, true);
                Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
            }

            Console.WriteLine();
        }