コード例 #1
0
ファイル: ClassIO.cs プロジェクト: DOSSTONED/testPrograms
        public static void WriteWordInfo(Word newWord)
        {
            FileInfo fInfo = new FileInfo(WorkingDir + newWord.WordName);

            if (fInfo.AlternateDataStreamExists(StreamNameFamili))
            {
                fInfo.DeleteAlternateDataStream(StreamNameFamili);
            }
            if (fInfo.AlternateDataStreamExists(StreamNameReviewedTimes))
            {
                fInfo.DeleteAlternateDataStream(StreamNameReviewedTimes);
            }

            FileStream fsFamili = fInfo.GetAlternateDataStream(StreamNameFamili, FileMode.Create).OpenWrite();

            byte[] bytesFamili = Encoding.ASCII.GetBytes(newWord.Familiarity.ToString());
            fsFamili.Write(bytesFamili, 0, bytesFamili.Length);
            fsFamili.Close();

            FileStream fsReview = fInfo.GetAlternateDataStream(StreamNameReviewedTimes, FileMode.Create).OpenWrite();

            byte[] bytesReview = Encoding.ASCII.GetBytes(newWord.ReviewedTimes.ToString());
            fsReview.Write(bytesReview, 0, bytesReview.Length);
            fsReview.Close();
        }
コード例 #2
0
ファイル: ClassIO.cs プロジェクト: DOSSTONED/testPrograms
        static public void LoadWords()
        {
            words = new List <Word>();
            string[] wordFiles = Directory.GetFiles(WorkingDir);
            foreach (string wordSingle in wordFiles)
            {
                string   curMeaning = File.ReadAllText(wordSingle);
                string   curName    = Path.GetFileNameWithoutExtension(wordSingle);
                double   famili     = 0;
                long     review     = 1;
                FileInfo fInfo      = new FileInfo(wordSingle);
                if (fInfo.AlternateDataStreamExists(StreamNameFamili))
                {
                    StreamReader sr = fInfo.GetAlternateDataStream(StreamNameFamili).OpenText();
                    famili = Convert.ToDouble(sr.ReadToEnd());
                }
                if (fInfo.AlternateDataStreamExists(StreamNameReviewedTimes))
                {
                    StreamReader sr = fInfo.GetAlternateDataStream(StreamNameReviewedTimes).OpenText();
                    review = Convert.ToInt64(sr.ReadToEnd());
                }

                words.Add(new Word(curName, curMeaning, famili, review));
            }
        }
コード例 #3
0
        private void RefreshList()
        {
            listBoxNew.Items.Clear();
            listBoxOld.Items.Clear();

            string[] words = Directory.GetFiles(zzz_WORDS_DIR_PATH);
            //textBoxWord.AutoCompleteCustomSource.AddRange(words);


            FileInfo fsInfo = null;

            for (int i = 0; i < words.Length; i++)
            {
                fsInfo = new FileInfo(words[i]);
                if (fsInfo.AlternateDataStreamExists(zzz_IS_NEW_STREAM_NAME))
                {
                    var info = fsInfo.GetAlternateDataStream(zzz_IS_NEW_STREAM_NAME).OpenText();
                    if (info.ReadToEnd().ToUpper() == "FALSE")
                    {
                        listBoxOld.Items.Add(Path.GetFileNameWithoutExtension(words[i]));
                        info.Close();
                        continue;
                    }
                }

                listBoxNew.Items.Add(Path.GetFileNameWithoutExtension(words[i]));
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: twiz718/Zoner
        private static void getZoneIdFromFileName(string fileName, bool quietMode)
        {
            var fileInfo = new FileInfo(fileName);

            // Read the "Zone.Identifier" stream, if it exists:
            if (fileInfo.AlternateDataStreamExists("Zone.Identifier"))
            {
                AlternateDataStreamInfo s = fileInfo.GetAlternateDataStream("Zone.Identifier", FileMode.Open);

                if (!quietMode)
                {
                    Console.WriteLine("Found the Zone.Identifier ADS in {0}. Size: {1} bytes. ", fileName, s.Size);
                    Console.WriteLine("--------------------[BEGIN]--------------------");
                }

                using (TextReader reader = s.OpenText())
                {
                    Console.WriteLine(reader.ReadToEnd());
                }

                if (!quietMode)
                {
                    Console.WriteLine("---------------------[END]---------------------");
                }
            }
            else
            {
                if (!quietMode)
                {
                    Console.WriteLine("Zone.Identifier ADS is not found on {0}", fileName);
                }
            }
        }
コード例 #5
0
        public void DetectWithIoNtfs()
        {
            var fileInfo = new FileInfo(path);

            foreach (var alternateDataStream in fileInfo.ListAlternateDataStreams())
            {
                Console.WriteLine("{0} - {1}", alternateDataStream.Name, alternateDataStream.Size);
            }

            // Read the "Zone.Identifier" stream, if it exists:
            if (fileInfo.AlternateDataStreamExists("Zone.Identifier"))
            {
                Console.WriteLine("Found zone identifier stream:");

                var s = fileInfo.GetAlternateDataStream("Zone.Identifier", FileMode.Open);
                using (TextReader reader = s.OpenText())
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
            else
            {
                Console.WriteLine("No zone identifier stream found.");
            }
        }
コード例 #6
0
ファイル: FileInfoExtensions.cs プロジェクト: mnjstwins/mpe
        /// <summary>
        /// Unblocks the file.
        /// </summary>
        /// <param name="file">Extension instance.</param>
        static public void Unblock(this FileInfo file)
        {
            if (file.Exists == false)
                throw new FileNotFoundException(String.Format(CultureInfo.InvariantCulture, "The specified file '{0}' could not be found.", file.FullName));

            if (file.AlternateDataStreamExists(FileInfoExtensions.ZoneIdentifierStreamName))
                file.DeleteAlternateDataStream(FileInfoExtensions.ZoneIdentifierStreamName);
        }
コード例 #7
0
        private void WordList_SelectedIndexChanged(object sender, EventArgs e)
        {
            var wordList = sender as ListBox;

            if (wordList == null)
            {
                return;
            }

            string wordFile = zzz_WORDS_DIR_PATH + (wordList.SelectedItem as string);

            if (!File.Exists(wordFile))
            {
                return;
            }

            FileInfo     fsInfo   = null;
            StreamReader wordRead = null;

            try
            {
                //wordRead = File.OpenText(wordFile);
                fsInfo   = new FileInfo(wordFile);
                wordRead = fsInfo.OpenText();

                textBoxWord.Text    = Path.GetFileNameWithoutExtension(wordFile);
                labelWordInCap.Text = Path.GetFileNameWithoutExtension(wordFile).ToUpper();
                //textBoxWordMeaning.Visible = false;
                //buttonWordShowMeaning.Visible = true;
                textBoxWordMeaning.Text = wordRead.ReadToEnd();

                if (fsInfo.AlternateDataStreamExists(zzz_IS_NEW_STREAM_NAME))
                {
                    var info = fsInfo.GetAlternateDataStream(zzz_IS_NEW_STREAM_NAME).OpenText();
                    if (info.ReadToEnd().ToUpper() == "FALSE")
                    {
                        checkBoxIsNew.Checked = false;
                    }
                    else
                    {
                        checkBoxIsNew.Checked = true;
                    }
                    info.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.InnerException.ToString(), ex.Source);
            }
            finally
            {
                if (wordRead != null)
                {
                    wordRead.Close();
                }
            }
        }
コード例 #8
0
        private async void StartProgramWithAdminRightsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Checks if the imput is empty
                if (String.IsNullOrWhiteSpace((string)DomainComboBox.Text) || String.IsNullOrWhiteSpace((string)UsernameComboBox.Text) || String.IsNullOrWhiteSpace(PasswordTextBox.Password))
                {
                    throw new ArgumentNullException();
                }

                ///Mapped drives are not available from an elevated prompt
                ///when UAC is configured to "Prompt for credentials" in Windows
                ///https://support.microsoft.com/en-us/help/3035277/mapped-drives-are-not-available-from-an-elevated-prompt-when-uac-is-co#detail%20to%20configure%20the%20registry%20entry
                ///https://stackoverflow.com/a/25908932/11189474
                System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog
                {
                    Filter           = "Application (*.exe)|*.exe|All Files|*.*",// "All Files|*.*|Link (*.lnk)|*.lnk"
                    Title            = "Select the applications you want to start",
                    DereferenceLinks = true,
                    Multiselect      = true
                };
                System.Windows.Forms.DialogResult result = fileDialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK || result == System.Windows.Forms.DialogResult.Yes)
                {
                    string[] paths = fileDialog.FileNames;
                    FileInfo file;
                    foreach (var path in paths)
                    {
                        file = new FileInfo(path);
                        if (file.Exists && file.AlternateDataStreamExists("Zone.Identifier"))
                        {
                            bool deletedIdentifier = file.DeleteAlternateDataStream("Zone.Identifier");
                            if (deletedIdentifier == false)
                            {
                                return;
                            }
                        }
                        await Task.Factory.StartNew(() =>
                        {
                            try
                            {
                                UACHelper.UACHelper.StartElevated(new ProcessStartInfo(path));
                            }
                            catch (Win32Exception win32ex)
                            {
                                GlobalVars.Loggi.Error(win32ex, win32ex.Message);
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                GlobalVars.Loggi.Error(ex, ex.Message);
            }
        }
コード例 #9
0
        private static bool UnblockFile(string path)
        {
            var file = new FileInfo(path);

            if (!file.AlternateDataStreamExists("Zone.Identifier"))
            {
                return(true);
            }

            return(file.DeleteAlternateDataStream("Zone.Identifier"));
        }
コード例 #10
0
        static public void Unblock(this FileInfo fileInfo)
        {
            if (fileInfo.Exists == false)
            {
                throw new FileNotFoundException("The specified file '" + fileInfo.FullName + "' could not be found.");
            }

            if (fileInfo.AlternateDataStreamExists(FileInfoExtensions.ZoneIdentifierStreamName))
            {
                fileInfo.DeleteAlternateDataStream(FileInfoExtensions.ZoneIdentifierStreamName);
            }
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: twiz718/Zoner
        private static void setZoneIdInFileName(string fileName, int zoneId, string referrerUrl, bool quietMode)
        {
            var fileInfo = new FileInfo(fileName);

            if (fileInfo.AlternateDataStreamExists("Zone.Identifier"))
            {
                deleteZoneIdFromFile(fileName, quietMode);
            }

            AlternateDataStreamInfo ads = fileInfo.GetAlternateDataStream("Zone.Identifier", FileMode.OpenOrCreate);

            writeZoneIdentifier(fileName, zoneId, referrerUrl, quietMode, ads);
        }
コード例 #12
0
        private bool IsDLLBlocked(string path)
        {
            FileInfo file = new FileInfo(path);

            if (file.AlternateDataStreamExists("Zone.Identifier"))
            {
                AlternateDataStreamInfo s = file.GetAlternateDataStream("Zone.Identifier", FileMode.Open);
                using (TextReader reader = s.OpenText())
                {
                    var zoneId = reader.ReadToEnd().ToUpperInvariant();
                    return(zoneId.Contains("ZONEID=3") || zoneId.Contains("ZONEID=4"));
                }
            }
            return(false);
        }
コード例 #13
0
        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName);
            }

            DirectoryInfo[] dirs = dir.GetDirectories();
            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            // Kill any running azurebcp
            NTHelper.KillProcess("azurebcp");

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            Parallel.ForEach(files, (currentFile) =>
            {
                string temppath = Path.Combine(destDirName, currentFile.Name);
                currentFile.CopyTo(temppath, true);
                FileInfo destination = new FileInfo(temppath);
                try
                {
                    if (destination.AlternateDataStreamExists("Zone.Identifier"))
                    {
                        destination.DeleteAlternateDataStream("Zone.Identifier");
                    }
                }
                catch { }
            });

            // If copying subdirectories, copy them and their contents to new location.
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
コード例 #14
0
ファイル: FileInfoEx.cs プロジェクト: uxifiit/UXI.Libs
        /// <summary>
        /// Deletes the Zone.Identifier data stream from the file, e.g. when it was marked as blocked by the operating system after downloading from the internet.
        /// </summary>
        /// <param name="file">File to unblock</param>
        /// <exception cref="ArgumentNullException">file is null</exception>
        /// <exception cref="FileNotFoundException">file does not exist</exception>
        public static void Unblock(this FileInfo file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            if (!file.Exists)
            {
                throw new FileNotFoundException("Unable to find the specified file.", file.FullName);
            }

            if (file.AlternateDataStreamExists(ZoneIdentifierStreamName))
            {
                file.DeleteAlternateDataStream(ZoneIdentifierStreamName);
            }
        }
コード例 #15
0
        private static void ShowContents(string fileName, string streamName)
        {
            FileInfo file = new FileInfo(fileName);

            Console.WriteLine($"{file.Name} - {file.Length:n0}");
            if (!string.IsNullOrWhiteSpace(streamName) && file.AlternateDataStreamExists(streamName))
            {
                AlternateDataStreamInfo s = file.GetAlternateDataStream(streamName, FileMode.Open);
                ShowContentsOfStream(file, s);
            }
            else if (string.IsNullOrWhiteSpace(streamName))
            {
                foreach (AlternateDataStreamInfo s in file.ListAlternateDataStreams())
                {
                    ShowContentsOfStream(file, s);
                }
            }
        }
コード例 #16
0
        private static void DeleteStream(string fileName, string streamName)
        {
            FileInfo file = new FileInfo(fileName);

            Console.WriteLine($"{file.Name} - {file.Length:n0}");
            if (!string.IsNullOrWhiteSpace(streamName) && file.AlternateDataStreamExists(streamName))
            {
                file.DeleteAlternateDataStream(streamName);
                Console.WriteLine($"    {streamName} deleted");
            }
            else if (string.IsNullOrWhiteSpace(streamName))
            {
                foreach (AlternateDataStreamInfo s in file.ListAlternateDataStreams())
                {
                    s.Delete();
                    Console.WriteLine($"    {s.Name} deleted");
                }
            }
        }
コード例 #17
0
        private IActionResult GetFile(FileInfo file, string dataStream = null)
        {
            if (file == null)
            {
                return(NotFound());
            }

            if (dataStream != null && file.Exists && file.AlternateDataStreamExists(dataStream))
            {
                return(File(file.GetAlternateDataStream(dataStream, FileMode.Open).OpenRead(), Mime.GetType(dataStream)));
            }

            if (dataStream == null && file.Exists)
            {
                return(PhysicalFile(file.FullName, Mime.GetType(file.Name)));
            }

            return(NotFound());
        }
コード例 #18
0
        public static string CopyToAlternateStream(string destinationPath, string sourcePath)
        {
            var destination = new FileInfo(destinationPath);
            var sourceName  = Path.GetFileName(sourcePath);

            if (destination.AlternateDataStreamExists(sourceName))
            {
                destination.DeleteAlternateDataStream(sourceName);
            }
            var destDataStream = destination.GetAlternateDataStream(sourceName);


            using (var destFileStream = destDataStream.OpenWrite())
                using (var sourceFileStream = File.OpenRead(sourcePath))
                {
                    sourceFileStream.CopyTo(destFileStream);
                }
            return(destination.Name + ":" + sourceName);
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: twiz718/Zoner
        private static void deleteZoneIdFromFile(string fileName, bool quietMode)
        {
            var fileInfo = new FileInfo(fileName);

            if (fileInfo.AlternateDataStreamExists("Zone.Identifier"))
            {
                if (!quietMode)
                {
                    Console.WriteLine("Deleting Zone.Identifier ADS from {0}", fileName);
                }
                fileInfo.DeleteAlternateDataStream("Zone.Identifier");
            }
            else
            {
                if (!quietMode)
                {
                    Console.WriteLine("Zone.Identifier ADS is not found in {0}", fileName);
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// Adds an internet zone identifier of "3" as an alternate data stream to the file
        /// </summary>
        /// <param name="fileLocation">File to add an alternate stream to</param>
        /// <remarks>More info here: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/6e3f7352-d11c-4d76-8c39-2516a9df36e8</remarks>
        private void AddZoneIdentifierBlockToFile(string fileLocation)
        {
            const string AlternateDataStreamNameToAdd = "Zone.Identifier";
            var          fi = new FileInfo(fileLocation);

            if (fi.AlternateDataStreamExists(AlternateDataStreamNameToAdd))
            {
                Console.WriteLine($"Alternate data stream already exists, so exiting {nameof(AddZoneIdentifierBlockToFile)} early.");
                return;
            }

            using (var fs = fi.GetAlternateDataStream(AlternateDataStreamNameToAdd).OpenWrite())
            {
                Console.WriteLine("Opened file for write");
                var content = new List <string>()
                {
                    "[ZoneTransfer]",
                    "ZoneId = 3"
                };
                content.ForEach(x => fs.Write(Encoding.UTF8.GetBytes(x + Environment.NewLine)));
                fs.Flush();
            }
        }
コード例 #21
0
        /// <summary>
        /// Called e.g. by explorer.exe. Missing is to call docbleach and then Office with the bleached document.
        /// </summary>
        /// <param name="Args"></param>
        private static void Bleach(string[] Args)
        {
            String OfficePath = "";

            // Get office path
            if (Args[0].Equals("/w"))
            {
                OfficePath = File.ReadAllText(ParentDirectory + "\\word");
            }
            else if (Args[0].Equals("/p"))
            {
                OfficePath = File.ReadAllText(ParentDirectory + "\\powerpnt");
            }
            else if (Args[0].Equals("/e"))
            {
                OfficePath = File.ReadAllText(ParentDirectory + "\\excel");
            }

            if (OfficePath.Length != 0)
            {
                int    l       = -1;
                String AllArgs = "";

                // Find document path.
                for (int i = 1; i < Args.Length; ++i)
                {
                    if (Args[i].Contains("\\"))
                    {
                        AllArgs += "\"" + Args[i] + "\" ";
                        l        = i;
                    }
                    else
                    {
                        AllArgs += Args[i] + " ";
                    }
                }

                if (l == -1)
                {
                    Logger.Error("Unable to find document: " + AllArgs);
                    return;
                }

                bool doBleach = false;

                try
                {
                    // Check ADS Zone
                    String OnlyBleachInternetFiles = ConfigurationManager.AppSettings["OnlyBleachInternetFiles"];

                    if (bool.Parse(OnlyBleachInternetFiles))
                    {
                        FileInfo F = new FileInfo(Args[l]);

                        if (F.AlternateDataStreamExists("Zone.Identifier"))
                        {
                            AlternateDataStreamInfo DataStream = F.GetAlternateDataStream("Zone.Identifier", FileMode.Open);
                            using (TextReader Reader = DataStream.OpenText())
                            {
                                String ADS = Reader.ReadToEnd();

                                if (ADS.Contains("ZoneId=3") || ADS.Contains("ZoneId=4"))
                                {
                                    doBleach = true;
                                }
                            }
                        }
                        else
                        {
                            Logger.Debug("No Zone.Identifier found");
                        }
                    }
                } catch (Exception e)
                {
                    Logger.Error("Unable to check ADS for " + Args[l], e);
                }

                if (doBleach)
                {
                    new DocBleachWrapper().Bleach(Args[l], ParentDirectory);
                }
                else
                {
                    Logger.Debug("Do not bleach: " + Args[l] + " not from internet");
                }

                // Call Office with bleached file.
                try
                {
                    Process.Start(OfficePath, AllArgs);
                } catch (Exception e)
                {
                    Logger.Error("Unable to start office: " + OfficePath + " " + AllArgs, e);
                }
            }
        }
コード例 #22
0
 /// <summary>
 /// FileInfo を指定して、ZoneID を持っているかどうかを返します。
 /// </summary>
 public static bool HasZoneID(this FileInfo body)
 {
     return(body.AlternateDataStreamExists("Zone.Identifier"));
 }
コード例 #23
0
        public bool Run(string gameExe, string extraGameArguments, out string errorMessage)
        {
            errorMessage = default;
            if (!this._client.CanRun(gameExe, extraGameArguments))
            {
                return(false);
            }

            gameExe ??= "Bannerlord.exe";
            var actualGameExe = Path.Combine(this.GameExeFolder, gameExe);

            if (string.IsNullOrEmpty(actualGameExe))
            {
                errorMessage = "Game executable could not be detected";
                this.Log().Error(errorMessage);
                return(false);
            }

            if (!File.Exists(actualGameExe))
            {
                errorMessage = $"{actualGameExe} could not be found";
                this.Log().Error(errorMessage);
                return(false);
            }

            foreach (var dll in this.GetAssemblies().Distinct())
            {
                try
                {
                    var fi = new FileInfo(dll);
                    if (!fi.Exists)
                    {
                        continue;
                    }
                    try
                    {
                        if (!fi.AlternateDataStreamExists("Zone.Identifier"))
                        {
                            continue;
                        }
                        var s = fi.GetAlternateDataStream("Zone.Identifier", FileMode.Open);
                        s.Delete();
                    }
                    catch (Exception e)
                    {
                        this.Log().Error(e);
                    }
                }
                catch
                {
                    //
                }
            }

            extraGameArguments ??= "";
            var args = extraGameArguments.Trim() + " " + this.GameArguments().Trim();

            this.Log().Warn($"Trying to execute: {actualGameExe} {args}");
            var info = new ProcessStartInfo
            {
                Arguments        = args,
                FileName         = actualGameExe,
                WorkingDirectory = Path.GetDirectoryName(actualGameExe) ?? throw new InvalidOperationException(),
                                         UseShellExecute = false
            };

            try
            {
                Process.Start(info);
            }
            catch (Exception e)
            {
                errorMessage = "Exception when trying to run the game. See the log for details";
                this.Log().Error(e);
                return(false);
            }

            return(true);
        }