예제 #1
0
        public void TestDeleteDirectory_JunctionPoint()
        {
            var targetFolder  = rootTestDir.Combine("ADirectory");
            var junctionPoint = rootTestDir.Combine("SymLink");

            targetFolder.CreateDirectory();

            try {
                var targetFile = targetFolder.Combine("AFile");

                File.Create(targetFile).Close();

                try {
                    JunctionPoint.Create(junctionPoint, targetFolder, overwrite: false);
                    Assert.IsTrue(File.Exists(targetFolder.Combine("AFile")), "File should be accessible.");
                    Assert.IsTrue(File.Exists(junctionPoint.Combine("AFile")), "File should be accessible via the junction point.");

                    Directory.Delete(junctionPoint, false);

                    Assert.IsTrue(File.Exists(targetFolder.Combine("AFile")), "File should be accessible.");
                    Assert.IsFalse(JunctionPoint.Exists(junctionPoint), "Junction point should not exist now.");
                    Assert.IsTrue(!File.Exists(junctionPoint.Combine("AFile")), "File should not be accessible via the junction point.");
                }
                finally {
                    File.Delete(targetFile);
                }
            }
            finally {
                Directory.Delete(targetFolder);
            }
        }
예제 #2
0
        private static void Link(string link, string target)
        {
            var linkDirectory   = new DirectoryInfo(link);
            var targetDirectory = new DirectoryInfo(target);

            if (linkDirectory.Exists)
            {
                // 如果目标目录存在,则检查一下这是否是一个目录联接。
                if (JunctionPoint.Exists(linkDirectory.FullName))
                {
                    // 如果是目录联接,则可以删除重建。
                    LinkCore(linkDirectory, targetDirectory);
                }
                else
                {
                    // 如果是文件夹,则检查里面是否存在文件,是否需要备份。
                    var hasContent = linkDirectory.EnumerateFileSystemInfos().Any();
                    if (hasContent)
                    {
                        linkDirectory.MoveTo($"{linkDirectory.FullName}.bak");
                    }
                    else
                    {
                        linkDirectory.Delete();
                        LinkCore(linkDirectory, targetDirectory);
                    }
                }
            }
            else
            {
                LinkCore(linkDirectory, targetDirectory);
            }
        }
            static void Delete(DirectoryInfo directory, int depth, IOResult logger)
            {
                if (JunctionPoint.Exists(directory.FullName))
                {
                    JunctionPoint.Delete(directory.FullName);
                }
                else if (!Directory.Exists(directory.FullName))
                {
                    return;
                }

                try
                {
                    foreach (var fileInfo in directory.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
                    {
                        File.Delete(fileInfo.FullName);
                    }

                    foreach (var directoryInfo in directory.EnumerateDirectories("*", SearchOption.TopDirectoryOnly))
                    {
                        var back = string.Join("\\", Enumerable.Repeat("..", depth));
                        Delete(directoryInfo, depth + 1, logger);
                    }

                    Directory.Delete(directory.FullName);
                }
                catch (Exception ex)
                {
                    logger.Fail(ex);
                }
            }
예제 #4
0
 public Item(FileSystemInfo info)
 {
     Info = info;
     if (info.IsReparsePoint())
     {
         if (JunctionPoint.Exists(info.FullName))
         {
             Type = ItemType.Junction;
             var reparse = JunctionPoint.GetTarget(info.FullName);
             LinkTarget = reparse.SubstituteName;
             PrintName  = reparse.PrintName;
         }
         else
         {
             Type       = info is FileInfo ? ItemType.FileSymlink : info is DirectoryInfo ? ItemType.DirSymlink : throw new Exception("unreachable 27117");
             LinkTarget = File.GetLinkTargetInfo(info.FullName).PrintName; // this should throw for reparse points of unknown types (ie neither junction nor symlink)
         }
     }
     else if (info is FileInfo)
     {
         Type = ItemType.File;
     }
     else if (info is DirectoryInfo)
     {
         Type = ItemType.Dir;
     }
     else
     {
         throw new Exception("unreachable 61374");
     }
 }
예제 #5
0
        public static bool MoveStorageToSource(Assignment prof, IProgress <long> sizeFromHell, object _lock, CancellationToken ct)
        {
            string sourceDir = prof.Source.FullName;
            string targetDir = prof.Target.FullName;// + @"\" + prof.Source.Name;

            Console.WriteLine("Moving " + sourceDir + " to " + targetDir + " started");
            bool returnStatus = false;

            try
            {
                /// find a junction, which has a different name, than the folder to be moved
                List <string> ListOfJunctions             = prof.Source.GetDirectories().Select(dir => dir.FullName).ToList().Where(str => JunctionPoint.Exists(@str)).ToList();
                List <string> ListOfTargets               = ListOfJunctions.Select(str => JunctionPoint.GetTarget(@str)).ToList();
                List <Tuple <string, string> > pairsOfJaT = new List <Tuple <string, string> >();
                for (int i = 0; i < ListOfJunctions.Count; i++)
                {
                    string JunctionName = (new DirectoryInfo(ListOfJunctions[i])).Name;
                    string TargetName   = (new DirectoryInfo(ListOfTargets[i])).Name;
                    if (JunctionName != TargetName)
                    {
                        pairsOfJaT.Add(new Tuple <string, string>(JunctionName, TargetName));
                    }
                }
                string renamedJunction = null;
                if (pairsOfJaT.Count > 0)
                {
                    renamedJunction = pairsOfJaT.FirstOrDefault(str => str.Item2 == prof.Source.Name).Item1;
                }
                if (renamedJunction != null)
                {
                    renamedJunction = prof.Target.Parent + @"\" + renamedJunction;
                }

                if (JunctionPoint.Exists(@targetDir))
                {
                    JunctionPoint.Delete(@targetDir);
                    returnStatus = CopyFolders(prof, sizeFromHell, _lock, ct);
                }
                else if (JunctionPoint.Exists(@renamedJunction))
                {
                    JunctionPoint.Delete(@renamedJunction);
                    returnStatus = CopyFolders(prof, sizeFromHell, _lock, ct);
                }
                if (returnStatus == true)
                {
                    DirectoryInfo deletableDirInfo = prof.Source;
                    deletableDirInfo.Delete(true);
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
            Console.WriteLine("Moving " + sourceDir + " to " + targetDir + " finished with " + returnStatus);
            return(returnStatus);
        }
예제 #6
0
 private void removeAllLinksToolStripMenuItem_Click(object sender, EventArgs e)
 {
     foreach (var v in model.Settings.InstalledVersions.OrderByDescending(version => version.VersionNumber))
     {
         if (JunctionPoint.Exists(Path.Combine(v.Folder, "mlc01", "usr", "title")))
         {
             JunctionPoint.Delete(Path.Combine(v.Folder, "mlc01", "usr", "title"));
         }
     }
     button3_Click(null, null);
 }
예제 #7
0
    public void IsJunctionPointTest()
    {
        var a = JunctionPoint.Exists(D());
        var b = JunctionPoint.Exists(J());
        var c = JunctionPoint.Exists(target);


        var d = JunctionPoint.IsReparsePoint(D());
        var e = JunctionPoint.IsReparsePoint(J());

        var f = JunctionPoint.IsReparsePoint(target);
    }
예제 #8
0
        public GameFolder([NotNull] DirectoryInfo directory, PauseToken pauseToken)
        {
            DirectoryInfo = directory;
            PauseToken    = pauseToken;
            IsJunction    = JunctionPoint.Exists(directory);
            if (IsJunction)
            {
                Size           = JUNCTION_POINT_SIZE;
                JunctionTarget = JunctionPoint.GetTarget(directory);
            }

            UpdatePropertiesFromSubdirectoriesAsync().Forget();
        }
예제 #9
0
        public TransferForm(string arg)
        {
            InitializeComponent();
            //Select the confirm button by default
            ActiveControl = confirmButton;
            origin        = arg;
            //Get any junctions that point to the folder being moved, and save where they were moved from if they exist
            SQLiteDataReader reader         = SQLiteManager.ExecuteSQLiteCommand("SELECT origin, target FROM junctions WHERE target = '" + origin + "';");
            string           databaseOrigin = null;

            if (reader.Read())
            {
                databaseOrigin = reader.GetString(reader.GetOrdinal("origin"));
            }
            reader.Close();
            SQLiteManager.CloseConnection();
            if (!JunctionPoint.Exists(origin))
            {
                //If the directory given is not a junction and is registered in the database...
                if (databaseOrigin != null)
                {
                    //Hide some elements to just show a message instead of getting input from the user
                    junctionArg = true;
                    destinationInput.Visible = false;
                    browseButton.Visible     = false;
                    //Assign the variables their proper values
                    target = origin;
                    origin = databaseOrigin;
                    //Give the user a message that this folder has been moved by this app, and ask if they want to move it back
                    label1.Text = target + " is already moved from " + origin + "! Would you like to move it back?";
                }
                else
                {
                    //If the directory given is not a junction and isn't registered in the database...
                    //Leave the window in its standard move with junction state, and put the last used location as the default
                    junctionArg           = false;
                    destinationInput.Text = Program.GetLastStorage() + "\\" + new DirectoryInfo(origin).Name;
                }
            }
            else
            {
                //if the directory given is a junction
                //Hide some elements to just show a message instead of getting input from the user
                junctionArg = true;
                destinationInput.Visible = false;
                browseButton.Visible     = false;
                //Get the directory the junction is pointing to and ask the user if he would like to move that folder back
                target      = JunctionPoint.GetTarget(origin);
                label1.Text = "Move " + target + " back to its original location at " + origin + "?";
            }
        }
예제 #10
0
        static bool IsDirectoryEmpty(string path)
        {
            if (Directory.EnumerateFiles(path).Any())
            {
                return(false);
            }

            if (Directory.EnumerateDirectories(path).Any(d => JunctionPoint.Exists(d) || !IsDirectoryEmpty(d)))
            {
                return(false);
            }

            return(true);
        }
예제 #11
0
        public void Create_VerifyExists_GetTarget_Delete()
        {
            string targetFolder  = Path.Combine(tempFolder, "ADirectory");
            string junctionPoint = Path.Combine(tempFolder, "SymLink");

            Directory.CreateDirectory(targetFolder);
            try
            {
                File.Create(Path.Combine(targetFolder, "AFile")).Close();
                try
                {
                    // Verify behavior before junction point created.
                    Assert.IsFalse(File.Exists(Path.Combine(junctionPoint, "AFile")),
                                   "File should not be located until junction point created.");

                    Assert.IsFalse(JunctionPoint.Exists(junctionPoint), "Junction point not created yet.");

                    // Create junction point and confirm its properties.
                    JunctionPoint.Create(junctionPoint, targetFolder, overwrite: false);

                    Assert.IsTrue(JunctionPoint.Exists(junctionPoint), "Junction point exists now.");

                    Assert.AreEqual(targetFolder, JunctionPoint.GetTarget(junctionPoint));

                    Assert.IsTrue(File.Exists(Path.Combine(junctionPoint, "AFile")),
                                  "File should be accessible via the junction point.");

                    // Delete junction point.
                    JunctionPoint.Delete(junctionPoint);

                    Assert.IsFalse(JunctionPoint.Exists(junctionPoint), "Junction point should not exist now.");

                    Assert.IsFalse(File.Exists(Path.Combine(junctionPoint, "AFile")),
                                   "File should not be located after junction point deleted.");

                    Assert.IsFalse(Directory.Exists(junctionPoint), "Ensure directory was deleted too.");
                }
                finally
                {
                    File.Delete(Path.Combine(targetFolder, "AFile"));
                }
            }
            finally
            {
                Directory.Delete(targetFolder);
            }
        }
예제 #12
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (junctionPathBox.Text.Length == 0)
     {
         ActiveControl = junctionPathBox;
         System.Media.SystemSounds.Exclamation.Play();
     }
     else
     {
         string origin = junctionPathBox.Text;
         if (JunctionPoint.Exists(origin))
         {
             string target = JunctionPoint.GetTarget(origin);
             SQLiteManager.AddJunction(origin, target);
             Close();
         }
     }
 }
        public void ExistsTest()
        {
            Helper.DemandTestDriveAvailable(TestDrive);
            //Helper.DemandElevated();

            var testFolder = Helper.GetTestFolder(TestDrive, "WriteTests", this);

            _fixture = new Fixture(() => Directory.Delete(testFolder, true));

            Directory.CreateDirectory(testFolder);
            var originalFolder = Path.Combine(testFolder, "original");

            Directory.CreateDirectory(originalFolder);
            var junction = Path.Combine(testFolder, "junction");

            JunctionPoint.Create(junction, originalFolder, true);
            Assert.IsTrue(Directory.Exists(junction));

            Assert.IsTrue(JunctionPoint.Exists(junction));
        }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        internal static void UpdateFeaturesForInstalledVersions(Model.Model model)
        {
            foreach (var version in model.Settings.InstalledVersions)
            {
                version.HasFonts              = HasFontsInstalled(version.Folder);
                version.HasOnlineFiles        = HasOnlineFiles(version.Folder);
                version.HasCemuHook           = HasCemuHookInstalled(version.Folder);
                version.HasPatch              = HasPatchInstalled(version.Folder);
                version.HasDlc                = HasDlcInstalled(version.Folder);
                version.HasControllerProfiles = HasControllerProfiles(version.Folder);
                if (version.HasDlc)
                {
                    version.DlcSource = JunctionPoint.GetTarget(Path.Combine(version.Folder, "mlc01", "usr", "title"));
                    if (JunctionPoint.Exists(Path.Combine(version.Folder, "mlc01", "usr", "title")))
                    {
                        if (Directory.Exists(version.DlcSource))
                        {
                            version.DlcType = 2;
                        }
                        else
                        {
                            version.DlcType = 3;
                        }
                    }
                    else
                    {
                        version.DlcType = 1;
                    }
                }
                else
                {
                    version.DlcType   = 0;
                    version.DlcSource = "";
                }

                if (version.Version.StartsWith("cemu"))
                {
                    version.Version = version.Name.Replace("cemu_", "").Replace("a", "").Replace("b", "").Replace("c", "").Replace("d", "").Replace("e", "").Replace("f", "").Replace("g", "");
                }
            }
        }
예제 #15
0
        public async Task <List <DirectoryInfo> > GetJunctions(DirectoryInfo selectedDirectory)
        {
            var junctions = new List <DirectoryInfo>();

            IsSearching = true;

            NumDirectories = 0;
            NumJunctions   = 0;

            using (TokenSource = new CancellationTokenSource())
            {
                var cancellationToken = TokenSource.Token;

                try
                {
                    await Task.Run(() => {
                        foreach (var info in selectedDirectory.EnumerateAllAccessibleDirectories())
                        {
                            cancellationToken.ThrowIfCancellationRequested();

                            NumDirectories++;
                            CurrentFolder = info.FullName;
                            if (JunctionPoint.Exists(info))
                            {
                                junctions.Add(info);
                                NumJunctions++;
                            }
                        }
                    }, cancellationToken);
                }
                catch (OperationCanceledException)
                {
                    // No work needed when user cancels search
                }
            }

            IsSearching = false;

            return(junctions);
        }
예제 #16
0
        public string MountSimple(int threadCount = 1)
        {
            if (Debugger.IsAttached)
            {
                threadCount = 1;
            }
            var mountname = SimpleMountName.Replace(":", "").Replace("\\", "-").Replace("/", "-");
            var mountpath = Path.Combine(Configuration_DokanFsRoot, mountname);

            Directory.CreateDirectory(mountpath);

            Console.WriteLine("Mounted.");
            Console.WriteLine(mountpath);

            var task     = Task.Run(() => this.Mount(mountpath, DokanOptions.NetworkDrive, threadCount));
            var attempts = 0;

            while (attempts < 30)
            {
                Thread.Sleep(100);
                attempts++;
                if (task.IsFaulted)
                {
                    throw task.Exception;
                }
                try
                {
                    if (!JunctionPoint.Exists(mountpath))
                    {
                        continue;
                    }
                    Directory.GetFiles(mountpath);
                    return(mountpath);
                }
                catch (Exception)
                {
                }
            }
            throw new TimeoutException();
        }
        static void InitTestApp()
        {
            var testAppPath         = Path.Combine(_binPath, "DebugApp");
            var testAppAssemblyPath = Path.Combine(_binPath, "DebugApp", TestAppExeName);

            var versionText       = FileVersionInfo.GetVersionInfo(testAppAssemblyPath).FileVersion;
            var appDeploymentPath = Path.Combine(_stagingPath, "v" + versionText);

            Directory.CreateDirectory(appDeploymentPath);

            foreach (var file in Directory.GetFiles(testAppPath))
            {
                var targetFile = Path.Combine(appDeploymentPath, Path.GetFileName(file));
                File.Copy(file, targetFile);
            }

            if (!JunctionPoint.Exists(_currentAppPath))
            {
                JunctionPoint.Create(_currentAppPath, appDeploymentPath);
            }
            Assert.That(Directory.Exists(_currentAppPath));
        }
        /// <summary>
        /// 删除指定路径的文件夹,此操作会递归删除文件夹内的所有文件,最后删除此文件夹自身。
        /// 如果目标文件夹是个连接点(Junction Point, Symbolic Link),则只会删除连接点而已,不会删除连接点所指目标文件夹中的文件。
        /// </summary>
        /// <param name="directory">要删除的文件夹。</param>
        /// <returns>包含执行成功和失败的信息,以及中间执行中方法自动决定的一些细节。</returns>
        public static IOResult Delete(DirectoryInfo directory)
        {
            if (directory is null)
            {
                throw new ArgumentNullException(nameof(directory));
            }

            var logger = new IOResult();

            logger.Log($"删除目录“{directory.FullName}”。");

            if (JunctionPoint.Exists(directory.FullName))
            {
                JunctionPoint.Delete(directory.FullName);
            }
            else if (!Directory.Exists(directory.FullName))
            {
                logger.Log($"要删除的目录“{directory.FullName}”不存在。");
                return(logger);
            }

            Delete(directory, 0, logger);
예제 #19
0
 static void ProcessDir(string dir)
 {
     try
     {
         string[] subs = Directory.GetDirectories(dir);
         if (verbose)
         {
             Console.WriteLine("Processing " + dir + ((subs.Length > 0) ? " - " + subs.Length + " subdir(s)" : ""));
         }
         foreach (string sub in subs)
         {
             if (JunctionPoint.Exists(sub))
             {
                 if (verbose)
                 {
                     Console.WriteLine("<JUNCTION>: " + sub);
                 }
                 ConvertJunction(sub);
             }
             else
             {
                 ProcessDir(sub);
             }
         }
     }
     catch (IOException)
     {
         if (verbose)
         {
             Console.WriteLine("Maybe.... <JUNCTION>: " + dir);
         }
         if (JunctionPoint.Exists(dir))
         {
             ConvertJunction(dir);
         }
     }
 }
예제 #20
0
        public bool IsLink(DirectoryInfo directoryInfo)
        {
            bool result = JunctionPoint.Exists(directoryInfo.FullName);

            return(result);
        }
예제 #21
0
        private void refreshDataGrid()
        {
            SQLiteDataReader reader          = SQLiteManager.ExecuteSQLiteCommand("SELECT * FROM junctions;");
            List <string>    sqlCommandQueue = new List <string>();

            while (reader.Read())
            {
                string origin = reader.GetString(reader.GetOrdinal("origin"));
                string target = reader.GetString(reader.GetOrdinal("target"));
                if (!JunctionPoint.Exists(origin))
                {
                    if (Directory.Exists(origin))
                    {
                        MessageBox.Show("The junction at " + origin + " that pointed to " + target + " has been replaced by a folder by the same name.  If you moved the folder back yourself this is fine, otherwise you might wanna look into this", "Junction is now a folder", MessageBoxButtons.OK);
                        sqlCommandQueue.Add("DELETE FROM junctions WHERE origin = '" + origin + "';");
                        Program.Log("WARNING: Junction at " + origin + " that pointed to " + target + " replaced by a folder with the same name");
                        continue;
                    }
                    else
                    {
                        MessageBox.Show("The junction at " + origin + " that pointed to " + target + " is not there, it could have been moved or deleted.", "Missing junction", MessageBoxButtons.OK);
                        sqlCommandQueue.Add("DELETE FROM junctions WHERE origin = '" + origin + "';");
                        Program.Log("WARNING: Junction at " + origin + " that pointed to " + target + " missing");
                        continue;
                    }
                }
                string realTarget = JunctionPoint.GetTarget(origin);
                if (realTarget != target)
                {
                    MessageBox.Show("The junction at " + origin + " has changed targets from " + target + " to " + realTarget + ".", "Moved junction target", MessageBoxButtons.OK);
                    sqlCommandQueue.Add("UPDATE junctions SET target = '" + realTarget + "' WHERE origin = '" + origin + "';");
                    target = realTarget;
                    Program.Log("WARNING: Junction at " + origin + " is now pointing to " + realTarget + ", was pointing to " + target);
                }
                if (!Directory.Exists(realTarget))
                {
                    MessageBox.Show("The folder at " + target + " is missing, the junction " + origin + " pointed to it.", "Folder missing", MessageBoxButtons.OK);
                    JunctionPoint.Delete(origin);
                    sqlCommandQueue.Add("DELETE FROM junctions WHERE origin = '" + origin + "';");
                    Program.Log("WARNING: " + target + " is missing, pointed to by junction at " + origin);
                }
            }
            SQLiteManager.CloseConnection();
            foreach (string s in sqlCommandQueue)
            {
                SQLiteManager.ExecuteSQLiteCommand(s);
                SQLiteManager.CloseConnection();
            }
            SQLiteManager.CloseConnection();

            //Create a DataSet object
            DataSet dataSet = new DataSet();

            //Get the adapter for the grid view, which will contain every junction in the table
            SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter("SELECT * FROM junctions;", SQLiteManager.GetSQLiteConnection());

            dataAdapter.Fill(dataSet);

            //Fill the view with the dataset
            dataGridView1.DataSource = dataSet.Tables[0].DefaultView;
            //Close the connection
            SQLiteManager.CloseConnection();

            if (dataGridView1.Rows.Count == 0)
            {
                restoreButton.Enabled = false;
                moveButton.Enabled    = false;
            }
            else
            {
                restoreButton.Enabled = true;
                moveButton.Enabled    = true;
            }
        }
 protected override void ProcessRecord()
 {
     WriteObject(JunctionPoint.Exists(path));
 }
예제 #23
0
        static void Recursive(string folder)
        {
            Extract  e     = null;
            FileInfo finfo = null;

            var buff = new byte[4096];
            IEnumerable <string> files = null;

            if (Path.GetPathRoot(folder) != CurrFolderRoot)
            {
                Log.Log <string>(LogLevel.Warning, new EventId(102, "ImageLoad"), $"Skipping folder {folder} we moved out of the specified ROOT {CurrFolderRoot}", null, (state, x) => { return($"{state}"); });
                return;
            }

            if (DiskFiles.Count > 0 && (DiskFiles.Count % 100) == 0)
            {
                Log.Log <string>(LogLevel.Information, new EventId(10, "ImageLoad status."), $"Gold image files, count is {DiskFiles.Count}", null, (state, ex) => { return($"{state}"); });
            }

            try {
                files = from afile in Directory.EnumerateFiles(folder, "*.*", SearchOption.TopDirectoryOnly)
                        select afile;
            } catch (Exception ex) {
                Log.Log <string>(LogLevel.Warning, new EventId(101, "ImageLoad"), $"Skipping folder {folder} {ex.Message}", ex, (state, x) => { return($"{state}"); });
            }

            if (files != null)
            {
                // get list of PE's we can hash
                foreach (var file in files)
                {
                    try
                    {
                        finfo = new FileInfo(file);
                        using (var fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                            fs.Read(buff, 0, buff.Length);

                        e = Extract.IsBlockaPE(buff);
                        if (e == null)
                        {
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Log <string>(LogLevel.Warning, new EventId(100, "ImageLoad"), $"Skipping file {finfo.FullName} {ex.Message}", ex, (state, x) => { return($"{state}"); });
                    }

                    if (e == null)
                    {
                        continue;
                    }

                    var bag = new ConcurrentBag <Tuple <uint, uint, string> >();
                    bag.Add(Tuple.Create <uint, uint, string>(e.SizeOfImage, e.TimeStamp, file));

                    DiskFiles.AddOrUpdate(Path.GetFileName(file).ToLower(), bag, (key, oldvalue) => { oldvalue.Add(Tuple.Create <uint, uint, string>(e.SizeOfImage, e.TimeStamp, file)); return(oldvalue); });
                }
            }

            // Parse subdirectories
            foreach (var subdir in Directory.EnumerateDirectories(folder, "*.*", SearchOption.TopDirectoryOnly))
            {
                try {
                    if (!JunctionPoint.Exists(subdir))
                    {
                        Recursive(subdir);
                    }
                } catch (Exception ex) {
                    Log.LogWarning(1, $"Problem with scanning folder: {subdir}", ex.Message);
                }
            }
        }
예제 #24
0
        public void Exists_IsADirectory()
        {
            File.Create(this.tempFolder.Combine("AFile")).Close();

            Assert.IsFalse(JunctionPoint.Exists(this.tempFolder.Combine("AFile")));
        }
예제 #25
0
        private async void button2_Click(object sender, EventArgs e)
        {
            if (!junctionArg)
            {
                //If this form is not involving an existing junction...
                //Find the target by getting the input from the user
                target = destinationInput.Text;

                //If the destinatino box is empty, select it, play a tone, and quit the method
                if (destinationInput.Text.Length == 0)
                {
                    ActiveControl = destinationInput;
                    System.Media.SystemSounds.Exclamation.Play();
                    return;
                }

                //Warn the user if they are attempting to put the folder into the folder, which will lead to recursion
                if (destinationInput.Text == origin.Substring(0, target.LastIndexOf('\\')))
                {
                    DialogResult recursionCaution = MessageBox.Show("You're attempting to move a folder within itself, this will put this folder within itself forever until the path is to long.", "Recursion Warning", MessageBoxButtons.OK);
                }
                else if (destinationInput.Text == origin)
                {
                    DialogResult recursionCaution = MessageBox.Show("You can't move a folder to where it currently is", "No Move Warning", MessageBoxButtons.OK);
                }
                else if (JunctionPoint.Exists(origin))
                {
                    DialogResult recursionCaution = MessageBox.Show("Moving a junction isn't allowed, please restore the junction at " + origin + " first.", "Can't Move Junction", MessageBoxButtons.OK);
                }
                else
                {
                    DialogResult confirmDialog = MessageBox.Show("Are you sure you want to create a junction at " + origin + " that links to " + target + "?", "Confirmation", MessageBoxButtons.YesNo);
                    if (confirmDialog == DialogResult.No)
                    {
                        return;
                    }
                    //If a directory already exists where the folder is going to be moved, ask the user if he is sure he wants to delete it
                    if (Directory.Exists(target) && Directory.EnumerateFileSystemEntries(target).Any())
                    {
                        //
                        DialogResult dialogResult = MessageBox.Show("There is already an existing folder at " + target + ", would you like to delete it?", "Existing Folder Found", MessageBoxButtons.YesNo);
                        if (dialogResult == DialogResult.Yes)
                        {
                            Directory.Delete(target, true);
                        }
                        else
                        {
                            return;
                        }
                    }

                    //Enable an ambiguous loading indicator
                    progressBar.Style = ProgressBarStyle.Marquee;

                    //Move the folder and make a junction
                    await Task.Run(() => JunctionManager.MoveWithJunction(origin, target));

                    //Take the final destination choice of the user and save it for next time
                    Program.SetLastStorage(target.Substring(0, target.LastIndexOf('\\')));
                }
            }
            else
            {
                //Enable an ambiguous loading indicator
                progressBar.Style = ProgressBarStyle.Marquee;
                //Move the folder back and replace the junction
                await Task.Run(() => JunctionManager.MoveReplaceJunction(origin, target));
            }
            //Close the form
            Close();
        }
예제 #26
0
        public void GetFolderStructure(Profile input)
        {
            //numberOfCalls++;
            LinkedFolders.Clear();
            StorableFolders.Clear();
            UnlinkedFolders.Clear();
            DuplicateFolders.Clear();

            List <string>        dGFolders = new List <string>();
            List <DirectoryInfo> gFolders  = new List <DirectoryInfo>();

            gFolders.AddRange(input.GameFolder.GetDirectories());
            List <DirectoryInfo> sFolders = new List <DirectoryInfo>();

            sFolders.AddRange(input.StorageFolder.GetDirectories());

            List <DirectoryInfo> _gFolders = new List <DirectoryInfo>();
            List <DirectoryInfo> _uFolders = new List <DirectoryInfo>();
            List <DirectoryInfo> _lFolders = new List <DirectoryInfo>();

            foreach (DirectoryInfo g in gFolders)
            {
                try
                {
                    bool isJunction = JunctionPoint.Exists(@g.FullName);

                    if (isJunction)
                    {
                        this.LinkedFolders.Add(new DirectoryInfo(JunctionPoint.GetTarget(@g.FullName)));
                    }
                    else
                    {
                        this.StorableFolders.Add(new DirectoryInfo(g.FullName));
                        _gFolders.Add(g);
                        dGFolders.Add(g.Name);
                    }
                }
                catch (IOException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            List <string>        dSFolders = new List <string>();
            List <DirectoryInfo> tmpList1  = sFolders.Where(n => LinkedFolders.Select(m => m.FullName).Contains(n.FullName) && !JunctionPoint.Exists(@n.FullName)).ToList();

            this.LinkedFolders.Clear();
            foreach (DirectoryInfo d in tmpList1)
            {
                this.LinkedFolders.Add(d);
                _lFolders.Add(d);
                dSFolders.Add(d.Name);
            }

            List <DirectoryInfo> tmpList = sFolders.Where(n => !LinkedFolders.Select(m => m.FullName).Contains(n.FullName) && !JunctionPoint.Exists(@n.FullName)).ToList();

            foreach (DirectoryInfo d in tmpList)
            {
                this.UnlinkedFolders.Add(d);
                _uFolders.Add(d);
                dSFolders.Add(d.Name);
            }
            DuplicateFolders = dGFolders.Intersect(dSFolders).ToList();
            _gFolders.RemoveAll(n => DuplicateFolders.Contains(n.Name));
            _uFolders.RemoveAll(n => DuplicateFolders.Contains(n.Name));
            _lFolders.RemoveAll(n => DuplicateFolders.Contains(n.Name));
            this.StorableFolders = _gFolders;
            this.UnlinkedFolders = _uFolders;
            this.LinkedFolders   = _lFolders;
        }
예제 #27
0
        static int Main(string[] args)
        {
            string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().FullName);
            string mappingsFile     = Path.Combine(currentDirectory, "mappings.txt");
            string lastGameModeFile = Path.Combine(currentDirectory, "lastGameMode.bin");

            // create missing files
            if (!File.Exists(mappingsFile))
            {
                using (var writer = File.CreateText(mappingsFile))
                {
                    writer.Write(@"################################################################################################################
# whitespace characters (space, tab, ...) and equal sign (=) all count as separators.
# 1st word is the name of folder (usually gamemode prefix) containing paks for this gamemode.
# all other words in the line are names for this gamemode (case insensitive).
# all names have to be unique. if not, they are ignored.
# whitespace in gamemode's name entered from input or as argument in UTPreparePaks.exe is not accounted for
# 
# example: you enter ""CaP t ure the fLA     G, bt"" it will be changed to ""CaPturethefLAG, bt""
# this string will then be compared to all names in this file (case insensitive)
# and then junctions to CTF and BT directory will be created in target directory
################################################################################################################
# lastGameMode.bin contains which gamemodes were last set for every target directory
# file is litle bit encrypted so that users wouldnt edit its content and potentially
# make it so that some unwanted junctions would not be deleted when no longer needed
################################################################################################################

AS		= AS Assault
BR		= BR BombingRun
BT		= BT BunnyTrack
CTF		= CTF CaptureTheFlag CaptureFlag
DM		= DM Deathmatch
Duel	= Duel 1v1 pvp
Elim	= Elim Elimination
FR		= FR FlagRun Blitz
KO		= KO Knockout"        );
                }
            }

            if (!File.Exists(lastGameModeFile))
            {
                File.Create(lastGameModeFile).Close();
            }



            // get target directory and gameModePrefix
            string        targetDirectory       = null;
            List <string> selectedGameModeNames = null;

            if (args.Length > 0)
            {
                targetDirectory = Path.GetFullPath(args[0]);
                if (args.Length > 1)
                {
                    selectedGameModeNames = new List <string>(args[1].Replace(" ", "").ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                }
                else
                {
                    Console.Write("Enter one or more gamemode names (comma separated): ");
                    selectedGameModeNames = new List <string>(Console.ReadLine().Replace(" ", "").ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                }

                var lastGameModeTargets = ParseLastGameModesFile(lastGameModeFile);
                var mappings            = ParseMappingsFile(mappingsFile);
                var selectedGameModes   = new List <string>();

                // get selected gamemodes
                foreach (var selectedGameModeName in selectedGameModeNames)
                {
                    if (mappings.TryGetValue(selectedGameModeName, out string selectedGameMode))
                    {
                        selectedGameModes.Add(selectedGameMode);
                    }
                    else
                    {
                        Console.WriteLine($"No mapping defined for '{selectedGameModeName}'. skipped.");
                    }
                }

                // get games modes used last time
                if (lastGameModeTargets.TryGetValue(targetDirectory, out List <string> lastGameModes))
                {
                    // go through every gamemode from last time
                    foreach (var lastGameMode in lastGameModes)
                    {
                        string lastJunctionDestination = Path.Combine(targetDirectory, lastGameMode);
                        if (!selectedGameModes.Contains(lastGameMode) && JunctionPoint.Exists(lastJunctionDestination)) // if supposed to delete and exists
                        {
                            JunctionPoint.Delete(lastJunctionDestination);                                              // delete
                        }
                    }
                }

                // go through every selected gamemode
                foreach (var selectedGameMode in selectedGameModes)
                {
                    string junctionSource      = Path.Combine(currentDirectory, selectedGameMode);
                    string junctionDestination = Path.Combine(targetDirectory, selectedGameMode);

                    if (!Directory.Exists(junctionSource))                           // directory on which junction will point doesnt exist yet
                    {
                        Directory.CreateDirectory(junctionSource);                   // make that directory
                    }
                    JunctionPoint.Create(junctionDestination, junctionSource, true); // finally create junction from targetDirectory to out gamemode directory
                }

                lastGameModeTargets[targetDirectory] = selectedGameModes;                 // sets which gamemodes were set this time
                WriteLastGameModes(lastGameModeFile, lastGameModeTargets);                // save used gamemodes
            }
            else
            {
                Console.WriteLine("UTPreparePaks <TargetDirectory> [GameModeName]");
                return(1);
            }

            return(0);
        }
예제 #28
0
        private void confirmButton_Click(object sender, EventArgs e)
        {
            //If the destinatino box is empty, select it, play a tone, and quit the method
            if (destinationInput.Text.Length == 0)
            {
                ActiveControl = destinationInput;
                System.Media.SystemSounds.Exclamation.Play();
                return;
            }

            //Warn the user if they are attempting to put the folder into the folder, which will lead to recursion
            if (destinationInput.Text == origin.Substring(0, origin.LastIndexOf('\\')))
            {
                DialogResult recursionCaution = MessageBox.Show("You're attempting to move a folder within itself, this will put this folder within itself forever until the path is to long.", "Recursion Warning", MessageBoxButtons.OK);
            }
            else if (destinationInput.Text == origin)
            {
                DialogResult recursionCaution = MessageBox.Show("You can't move a folder to where it currently is", "No Move Warning", MessageBoxButtons.OK);
            }
            else if (JunctionPoint.Exists(origin))
            {
                DialogResult recursionCaution = MessageBox.Show("Moving a junction isn't allowed, please restore the junction at " + origin + " first.", "Can't Move Junction", MessageBoxButtons.OK);
            }
            else
            {
                //If this form is not involving an existing junction...
                //Find the target by getting the input from the user
                target = destinationInput.Text;

                DialogResult confirmDialog = MessageBox.Show("Are you sure you want to move " + origin + " to " + target + " and update the junction at " + junction + " to point to it?", "Confirmation", MessageBoxButtons.YesNo);
                if (confirmDialog == DialogResult.No)
                {
                    return;
                }

                //If a directory already exists where the folder is going to be moved, ask the user if he is sure he wants to delete it
                if (Directory.Exists(target) && Directory.EnumerateFileSystemEntries(target).Any())
                {
                    //
                    DialogResult dialogResult = MessageBox.Show("There is already an existing folder at " + target + ", would you like to delete it?", "Existing Folder Found", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        Directory.Delete(target, true);
                    }
                    else
                    {
                        return;
                    }
                }

                //Enable an ambiguous loading indicator
                progressBar.Style = ProgressBarStyle.Marquee;

                //Move the folder and make a junction
                Program.CopyFolder(origin, target);
                Directory.Delete(origin, true);

                Program.Log("INFO: Moved " + origin + " to " + target);

                JunctionPoint.Create(junction, target, true);

                Program.Log("INFO: Updated junction at " + junction + " to point to " + target);

                SQLiteManager.ExecuteSQLiteCommand("UPDATE junctions SET target = '" + target + "' WHERE origin = '" + junction + "';");

                Close();
            }
        }
예제 #29
0
        void RecursiveGenerate(string aPath, ParallelOptions po)
        {
            var TmpList                = new List <string>();
            var CheckedList            = new List <string>();
            IEnumerable <string> files = null;

            try
            {
                // First get the file list inclusive of our file extensions list
                files = from afile in Directory.EnumerateFiles(
                    aPath, "*.*",
                    SearchOption.TopDirectoryOnly)
                        let file = afile.ToUpper()
                                   from just in ScanExtensions
                                   where file.EndsWith(just)
                                   select file;
            } catch (Exception ex) {
                string err = $"Unable to enumerate folder {aPath}.  {ex.ToString()}";
                if (aPath.Equals(InitialScanFolder))
                {
                    LogEx(0, $"Canceling, failed with initial folder. {err}");
                    source.Cancel();
                    return;
                }
                else
                {
                    LogEx(1, err);
                }
            }

            bool banner = false;

            // strip out any banned items
            foreach (var file in files)
            {
                foreach (var banned in MaskedEntries)
                {
                    if (file.EndsWith(banned))
                    {
                        banner = true;
                        break;
                    }
                }
                if (!banner)
                {
                    TmpList.Add(file);
                }

                banner = false;
            }

            // get list of PE's we can hash
            foreach (var check in TmpList)
            {
                if (source.IsCancellationRequested)
                {
                    return;
                }

                var carved = CheckFile(check);
                if (carved != null)
                {
                    LoadList.Push(carved);
                    Interlocked.Increment(ref LoadCount);
                    if (LoadCount % 100 == 0 && GenerateSW.Elapsed.TotalSeconds > 0)
                    {
                        WriteColor(ConsoleColor.Gray, $"Loaded {LoadCount} code files. {(LoadCount / GenerateSW.Elapsed.TotalSeconds):N0} per second.");
                    }
                }
            }

            // Parse subdirectories
            foreach (var subdir in Directory.EnumerateDirectories(aPath, "*.*", SearchOption.TopDirectoryOnly))
            {
                var dirs = from banned in MaskedEntries
                           where !subdir.ToUpper().Contains(banned)
                           select banned;
                if (dirs.Count() > 0)
                {
                    try {
                        if (!JunctionPoint.Exists(subdir))
                        {
                            RecursiveGenerate(subdir, po);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogEx(1, $"Problem with scanning folder: {subdir} Exeption: {ex.Message}");
                    }
                }
            }
        }
예제 #30
0
 public void Exists_NoSuchFile() => Assert.IsFalse(JunctionPoint.Exists(this.tempFolder.Combine("$$$NoSuchFolder$$$")));