コード例 #1
0
        /// <summary>
        /// http://stackoverflow.com/questions/1600962/displaying-the-build-date
        /// </summary>
        public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null)
        {
            var       filePath                = assembly.Location;
            const int c_PeHeaderOffset        = 60;
            const int c_LinkerTimestampOffset = 8;

            var buffer = new byte[2048];

            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
                stream.Read(buffer, 0, 2048);

            var offset           = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
            var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
            var epoch            = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            var linkTimeUtc = epoch.AddSeconds(secondsSince1970);

            var tz        = target ?? TimeZoneInfo.Local;
            var localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz);

            return(localTime);
        }
コード例 #2
0
        public void TestReplaceOnFileWithout_UTF8_BOM(SearchType type, GrepSearchOption option, string searchFor, string replaceWith)
        {
            // Test for Issue #227
            Utils.CopyFiles(sourceFolder + "\\TestCase15", destinationFolder + "\\TestCase15", null, null);
            GrepCore core = new GrepCore();
            List <GrepSearchResult> results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase15", "books.xml"),
                                                          type, searchFor, option, -1);

            Assert.Equal(1, results.Count);
            string testFile = Path.Combine(destinationFolder, @"TestCase15\books.xml");
            Dictionary <string, string> files = new Dictionary <string, string>
            {
                { testFile, Guid.NewGuid().ToString() + ".xml" }
            };

            core.Replace(files, type, searchFor, replaceWith, option, -1);

            using (FileStream stream = File.Open(testFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (StreamReader reader = new StreamReader(stream, true))
                {
                    Assert.Equal(Encoding.UTF8, reader.CurrentEncoding);
                    // check there is no BOM
                    int bb = reader.BaseStream.ReadByte();
                    Assert.NotEqual(0xEF, bb);
                    Assert.Equal('<', bb);
                    bb = reader.BaseStream.ReadByte();
                    Assert.NotEqual(0xBB, bb);
                    bb = reader.BaseStream.ReadByte();
                    Assert.NotEqual(0xBF, bb);
                }
            var fileContent = File.ReadAllLines(destinationFolder + "\\TestCase15\\books.xml", Encoding.UTF8);

            Assert.Equal(38, fileContent.Length);
            Assert.Equal("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", fileContent[0]);
            Assert.Equal("  <book category=\"general\">", fileContent[8]);
        }
コード例 #3
0
        private static KeyValue LoadFromFile(string path, bool asBinary)
        {
            if (!File.Exists(path))
            {
                return(null);
            }

            try
            {
                using (var input = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var kv = new KeyValue();

                    if (asBinary)
                    {
                        if (!kv.TryReadAsBinary(input))
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        if (!kv.ReadAsText(input))
                        {
                            return(null);
                        }
                    }

                    return(kv);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #4
0
        public static bool IsFileLocked(this string file)
        {
            FileStream stream = null;

            try
            {
                stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.None);
            }
            catch (IOException)
            {
                //the file is unavailable because it is:
                //still being written to
                //or being processed by another thread
                //or does not exist (has already been processed)
                return(true);
            }
            finally
            {
                stream?.Close();
            }

            //file is not locked
            return(false);
        }
コード例 #5
0
        void ViewModel_ShowPreview(object sender, EventArgs e)
        {
            bool reopenSearchPanel = false;

            if (!searchPanel.IsClosed)
            {
                reopenSearchPanel = true;
                // no callback from the close call
                searchPanel.SearchResultsChanged -= SearchPanel_SearchResultsChanged;
                searchPanel.Close();
            }

            textEditor.Clear();
            textEditor.Encoding           = ViewModel.Encoding;
            textEditor.SyntaxHighlighting = ViewModel.HighlightingDefinition;
            textEditor.TextArea.TextView.LinkTextForegroundBrush = Application.Current.Resources["AvalonEdit.Link"] as Brush;
            for (int i = textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
            {
                if (textEditor.TextArea.TextView.LineTransformers[i] is PreviewHighlighter)
                {
                    textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
                }
            }

            if (ViewModel.HighlightsOn && !ViewModel.HighlightDisabled && !ViewModel.IsPdf)
            {
                textEditor.TextArea.TextView.LineTransformers.Add(new PreviewHighlighter(ViewModel.GrepResult));
            }

            try
            {
                if (!ViewModel.IsLargeOrBinary)
                {
                    if (!string.IsNullOrWhiteSpace(ViewModel.FilePath))
                    {
                        bool isRTL = Utils.IsRTL(ViewModel.FilePath, ViewModel.Encoding);
                        textEditor.FlowDirection = isRTL ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;

                        using (FileStream stream = File.Open(ViewModel.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            textEditor.Load(stream);
                        }
                        if (!string.IsNullOrEmpty(textEditor.Text))
                        {
                            if (reopenSearchPanel)
                            {
                                searchPanel.Open();
                            }

                            UpdatePositionMarkers();

                            textEditor.ScrollTo(ViewModel.LineNumber, 0);
                        }
                    }
                    else
                    {
                        textEditor.Text = "";
                        ViewModel.ClearPositionMarkers();
                    }
                }
            }
            catch (Exception ex)
            {
                textEditor.Text = "Error opening the file: " + ex.Message;
            }
            finally
            {
                if (reopenSearchPanel)
                {
                    searchPanel.SearchResultsChanged += SearchPanel_SearchResultsChanged;
                }
            }
        }
コード例 #6
0
        private static void ExtractToTempFile(Stream input, string filePath, string diskFile, string innerFileName, string[] intermediateFiles)
        {
            using (SevenZipExtractor extractor = new SevenZipExtractor(input))
            {
                if (intermediateFiles.Length > 0)
                {
                    int index = -1;
                    if (extractor.ArchiveFileData.Count == 1)
                    {
                        index = 0;
                    }
                    else
                    {
                        string name = intermediateFiles.First();
                        var    fd   = extractor.ArchiveFileData.FirstOrDefault(f => string.Equals(f.FileName, name));
                        if (fd != null)
                        {
                            index = fd.Index;
                        }
                    }

                    if (index > -1)
                    {
                        using (Stream stream = new MemoryStream())
                        {
                            extractor.ExtractFile(index, stream);
                            string[] newIntermediateFiles = intermediateFiles.Skip(1).ToArray();

                            ExtractToTempFile(stream, filePath, diskFile, innerFileName, newIntermediateFiles);
                        }
                    }
                }
                else
                {
                    int index = -1;
                    if (extractor.ArchiveFileData.Count == 1)
                    {
                        index = 0;
                    }
                    else
                    {
                        var fd = extractor.ArchiveFileData.FirstOrDefault(f => string.Equals(f.FileName, innerFileName));
                        if (fd != null)
                        {
                            index = fd.Index;
                        }
                    }

                    if (index > -1)
                    {
                        using (FileStream stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            try
                            {
                                extractor.ExtractFile(index, stream);
                            }
                            catch (Exception ex)
                            {
                                logger.Error(ex, string.Format(CultureInfo.CurrentCulture, "Failed extract file {0} from archive '{1}'", innerFileName, diskFile));
                            }
                        }
                    }
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Flushes the record for the keyword (and its entire gang) out to disk.  You must call this from inside a lock.
        /// </summary>
        /// <param name="wiwi"></param>
        /// <param name="create_directory_first"></param>
        private void FlushKeyword_LOCK(WordInWordIndex wiwi, bool create_directory_first)
        {
            // If this is not loaded, there is nothing to do
            if (!wiwi.IsLoaded)
            {
                return;
            }

            // If this one doesnt need flushing, don't do it
            if (!wiwi.needs_flushing)
            {
                return;
            }

            try
            {
                // Build up the gangs
                int gang_start = GangStart(wiwi.WordId);
                List <WordEntry> word_entrys = new List <WordEntry>();

                string filename_temp = Path.GetTempFileName();
                using (FileStream fs = File.Open(filename_temp, FileMode.Create))
                {
                    {
                        for (int i = 0; i < GANG_SIZE; ++i)
                        {
                            // If this is the last gang, there may be too few words
                            if (word_in_word_indexes.Count <= gang_start + i)
                            {
                                break;
                            }

                            if (null == word_in_word_indexes[gang_start + i].DocumentIds)
                            {
                                throw new Exception("Document ids should not be null");
                            }

                            WordEntry word_entry = new WordEntry
                            {
                                Word             = word_in_word_indexes[gang_start + i].Word,
                                DocumentIds      = word_in_word_indexes[gang_start + i].DocumentIds,
                                DocumentIdsCount = word_in_word_indexes[gang_start + i].DocumentIdsCount
                            };

                            word_entrys.Add(word_entry);
                        }

                        Serializer.Serialize <List <WordEntry> >(fs, word_entrys);
                    }
                }

                // Move the temp file into place
                string filename = Filename_GangList(wiwi.WordId);

                // Create the directory for the file
                if (create_directory_first)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filename));
                }

                FileTools.MoveSafelyWithOverwriting(filename_temp, filename);

                // Mark the gang as flushed
                for (int i = 0; i < GANG_SIZE; ++i)
                {
                    // If this is the last gang, there may be too few words
                    if (word_in_word_indexes.Count <= gang_start + i)
                    {
                        break;
                    }

                    word_in_word_indexes[gang_start + i].last_flushed   = DateTime.UtcNow;
                    word_in_word_indexes[gang_start + i].needs_flushing = false;
                }
            }
            catch (Exception ex)
            {
                //  If we have an exception, it is probably because we have not created the directory, so try that
                if (!create_directory_first)
                {
                    FlushKeyword_LOCK(wiwi, true);
                }
                else
                {
                    // If we have created the directory before, then there must be some other problem
                    throw ex;
                }
            }
        }
コード例 #8
0
 public override Stream Open(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(AfsFile.Open(path, mode, access, share));
 }
コード例 #9
0
 public override Stream Open(string path, FileMode mode)
 {
     return(AfsFile.Open(path, mode));
 }