DiscardBufferedData() public method

public DiscardBufferedData ( ) : void
return void
        public void LogFileMaxSize( )
        {
            const int MaxSize = 32767;

            // Fill the log file
            const string alpabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            using ( StreamWriter writer = File.CreateText( LogFilePath ) )
            {
                for ( int i = 0; i < MaxSize / alpabet.Length; ++i )
                {
                    writer.Write( alpabet );
                }
                writer.Write( alpabet.Substring( 0, MaxSize % alpabet.Length ) );
            }

            const string logStr = "Hello World";
            TestLogger logger = new TestLogger();
            logger.Log( logStr );

            using ( FileStream stream = File.OpenRead( LogFilePath ) )
            {
                Assert.AreEqual( MaxSize, stream.Length );

                // Did we shift the existing contents?
                StreamReader reader = new StreamReader( stream );
                Assert.AreEqual( alpabet[logStr.Length], (char) reader.Read() );

                // Did we append the new log?
                stream.Position = MaxSize - logStr.Length;
                reader.DiscardBufferedData();
                Assert.AreEqual( logStr, reader.ReadToEnd() );
            }
        }
Example #2
0
 public EdiStream(Stream ediStream)
 {
     _streamReader = new StreamReader(ediStream);
     _interchangeContext = new InterchangeContext(_streamReader);
     ediStream.Position = 0;
     _streamReader.DiscardBufferedData();
 }
        //analyze file and returns an array with all lines
        private string[] analyzeFile()
        {
            int counter = 0;
            string line;

            System.IO.StreamReader file = new System.IO.StreamReader(filePath.Text);
            var count = File.ReadLines(filePath.Text).Count();

            string[] dataEntries = new string[count];

            file.DiscardBufferedData();
            file.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            file.BaseStream.Position = 0;

            //save all data entries to the array dataEntires
            while ((line = file.ReadLine()) != null)
            {
                dataEntries[counter] = line;
                counter++;
            }

            file.Close();

            return dataEntries;
        }
Example #4
0
        public string BuildQuery(string WordListFile, int MaxWords)
        {
            string Query = null;

            FileStream FS = new FileStream(WordListFile, FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader SR = new StreamReader(FS);

            string text = SR.ReadToEnd();

            Regex RE = new Regex("\n", RegexOptions.Multiline);
            MatchCollection matches = RE.Matches(text);

            int numSearchTerms = random.Next(1, MaxWords);

            for (int i = 0; i < numSearchTerms; i++)
            {
                string temp = null;
                SR.DiscardBufferedData();
                SR.BaseStream.Position = random.Next(0, (int)SR.BaseStream.Length);
                temp = SR.ReadLine();
                temp = SR.ReadLine();

                Query += temp + " ";
            }

            SR.Close();
            FS.Close();

            return Query.Trim();
        }
Example #5
0
        /// <summary>
        /// Return last line of a text file
        /// </summary>
        /// <param name="filePath">File path</param>
        /// <returns></returns>
        public static string GetLastLineOfFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
                throw new ArgumentNullException("filePath");

            if (!FileSystem.File.Exists(filePath))
                throw new FileNotFoundException("File not found: " + filePath);

            using (var sr = new StreamReader(filePath))
            {
                sr.BaseStream.Seek(0, SeekOrigin.End);

                long pos = -1;

                while (sr.BaseStream.Length + pos > 0)
                {
                    sr.BaseStream.Seek(pos, SeekOrigin.End);
                    var c = sr.Read();
                    sr.DiscardBufferedData();

                    if (c == Convert.ToInt32('\n'))
                    {
                        sr.BaseStream.Seek(pos + 1, SeekOrigin.End);
                        return sr.ReadToEnd();
                    }

                    --pos;
                }
            }

            return null;
        }
Example #6
0
 public EdiStream(Stream ediStream, string definitionsAssemblyName = null)
 {
     _streamReader = new StreamReader(ediStream);
     _interchangeContext = new InterchangeContext(_streamReader, definitionsAssemblyName);
     ediStream.Position = 0;
     _streamReader.DiscardBufferedData();
 }
Example #7
0
        static void Main(string[] args)
        {
            string InputFileName = args[0];
            string Outputfolder = args[1];
            int OutputCount = int.Parse(args[2]);
            StreamReader reader = new StreamReader(InputFileName);

            //Count number of lines
            Console.WriteLine("Compute Lines..");
            int count = 0;
            while (!reader.EndOfStream)
            {
                reader.ReadLine();
                count++;
            }

            Console.WriteLine("Total lines: " + count);
            int chunkSize = count / OutputCount;
            reader.DiscardBufferedData();
            for (int i = 0; i < OutputCount && !reader.EndOfStream ; ++i)
            {
                Console.WriteLine("Writing {0} document...", i);
                StreamWriter writer = new StreamWriter(Outputfolder + "\\out" + i + ".tsv");
                for(int j = chunkSize * i; j < chunkSize*(i + 1) && !reader.EndOfStream; j++)
                {
                    writer.WriteLine(reader.ReadLine());
                }
                writer.Flush();
            }
            Console.Read();
        }
Example #8
0
        private static void convertToField(int spaceCount, StringBuilder fieldBuilder, StreamReader reader, ClassTemplate meta, int language_type)
        {
            if (fieldBuilder == null || reader == null || meta == null)
                return;
            //文件流回到开始的位置
            reader.DiscardBufferedData();
            reader.BaseStream.Seek(0, SeekOrigin.Begin);
            reader.BaseStream.Position = 0;

            string line;
            while ((line = reader.ReadLine()) != null)
            {

                line = findAndReplace(line, "%field_type%", meta.Field_type);
                line = findAndReplace(line, "%field_name%", meta.Field_name);
                line = findAndReplace(line, "%Field_name%", meta.Upper_field_name);
                if (line.IndexOf("%annotation%")!=-1&&string.IsNullOrEmpty(meta.Annotation))
                {
                    continue;
                }
                line = findAndReplace(line, "%annotation%", meta.Annotation);
                fieldBuilder.Append(getDesignatedSpace(spaceCount)).Append(line).Append("\r\n");

            }
        }
 public TilesetTableTest()
 {
     var tilesetTableMemoryStream = FileStreams.TilesetTableStream();
     var tilesetTableStreamReader = new StreamReader(tilesetTableMemoryStream);
     tilesetTableStreamReader.DiscardBufferedData();
     tilesetTableMemoryStream.Position = 0;
     var tilesetTable = new TilesetTable(null, tilesetTableStreamReader);
 }
Example #10
0
        public Board()
        {
            NumberOfSteps = 0;
            Rand = new Random();

            try
            {
                using (var board = new StreamReader("Board.txt"))
                {
                    var i = 0;
                    var j = 0;

                    while (board.EndOfStream != true)
                    {
                        board.ReadLine();
                        Boardx++;
                    }
                    board.DiscardBufferedData();
                    board.BaseStream.Position = 0;

                    BoardChars = new char[Boardx][];

                    while (board.EndOfStream != true && i < Boardx)
                    {
                        var line = board.ReadLine();
                        if (line != null)
                        {
                            var readLine = line.Trim('\uFEFF');
                            {
                                var array = readLine.ToCharArray();
                                ArrayLength = readLine.Length;
                                BoardChars[i] = new char[ArrayLength + 1];
                                while (j < ArrayLength)
                                {
                                    BoardChars[i][j] = array[j];
                                    BoardChars[i][j + 1] = '\n';
                                    //Write(BoardChars[i][j]);
                                    j++;
                                }
                                //WriteLine();
                            }
                        }
                        j = 0;
                        i++;
                    }
                    DisplayBoard();
                }
                //WriteLine("\nPress F12 to quit.");
            }
            catch (FileNotFoundException e)
            {
                WriteLine("Attention ! Fichier : " + e.Source + " introuvable !");
            }
            catch (DirectoryNotFoundException e)
            {
                WriteLine("Attention ! Dossier : " + e.Source + " introuvable !");
            }
        }
Example #11
0
 public static string LoadTextResource(Assembly assembly, string sResourceName)
 {
     string sReturn = "";
     using (var sr = new StreamReader(assembly.GetManifestResourceStream(sResourceName)))
     {
         sReturn = sr.ReadToEnd();
         sr.DiscardBufferedData();
         sr.Close();
     }
     return sReturn;
 }
Example #12
0
        public static SeismicBitmapInfo[] getBitmapsInfoFromDirectory()
        {
            var applicationDirectory = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Resources\\";

            //will return a list of seismic data
            string[] jpgFiles = Directory.GetFiles(applicationDirectory, imageJPGExtension);
            string[] dataFiles = Directory.GetFiles(applicationDirectory, dataExtension);

            if (dataFiles.Length != 1 || jpgFiles.Length == 0)
                return null;

            StreamReader dataReader = new StreamReader(dataFiles[0]);
            int lineCount = 0;
            while (dataReader.ReadLine() != null)
                lineCount++;

            dataReader.BaseStream.Position = 0;
            dataReader.DiscardBufferedData();

            if (lineCount % 3 != 0)
                return null;//The number of lines must be a multiple of 3, because 1 piece of "data" requires 3 lines, line name, 2 lat/long points

            int numberOfSeismicImages = lineCount / 3;

            if (numberOfSeismicImages != jpgFiles.Length)
                return null;

            List<SeismicBitmapInfo> bitmapInfoCollection = new List<SeismicBitmapInfo>();
            string[] dataStrings = new string[3];
            SeismicBitmapInfo newinfo;
            for (int i = 0; i < numberOfSeismicImages; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    dataStrings[j] = dataReader.ReadLine();
                }

                string lineFileName = getLineFileFromString(applicationDirectory, dataStrings[0]);
                if (!jpgFiles.Contains(lineFileName))
                    continue;//You only create and populate info for lines that both exist in the data file, and have corresponding image file

                newinfo = new SeismicBitmapInfo();
                newinfo.line = new LineSegment(getLatLongPointFromString(dataStrings[1]), getLatLongPointFromString(dataStrings[2]));
                newinfo.bitmapName = lineFileName;
                newinfo.bitmapImage = new BitmapImage(new Uri(lineFileName, UriKind.Relative));
                newinfo.lineNumber = getLineNumberFromString(dataStrings[0]);
                //bitmapInfoCollection.Add(newinfo);
                insertSeismicInfoIntoList(bitmapInfoCollection, newinfo);
            }

            //bitmapInfoCollection.Reverse();

            return bitmapInfoCollection.ToArray();
        }
Example #13
0
        static void Main(string[] args)
        {
            StreamReader inputFile;
            StreamReader tranInputFile;

            char[] code = new char[3];
            string tranCode;
            string tCode;

            string[] fileNameSuffix = { "1", "2", "3" };

            StreamWriter logSession = new StreamWriter("./../../../LogSession.txt",true);
            for (int i = 0; i < fileNameSuffix.Length; i++)
            {

                inputFile = new StreamReader("./../../../" + "MainData" + fileNameSuffix[i] + ".txt");
                tranInputFile = new StreamReader("./../../../" + "TransData" + fileNameSuffix[i] + ".txt");
                CodeIndex index = new CodeIndex(fileNameSuffix[i]);
                logSession.WriteLine("==============");
                logSession.WriteLine("PROCESSING TransData " + fileNameSuffix[i].ToString());
                while (!tranInputFile.EndOfStream)
                {
                    string[] tranLine = tranInputFile.ReadLine().Split(' ');

                    tranCode = tranLine[0];  //QC
                    tCode = (tranLine[1]);  //***

                    short DRP = index.QueryByCode(tCode);

                    if (DRP == -1)
                    {

                    }
                    else
                    {
                        inputFile.DiscardBufferedData();
                        inputFile.BaseStream.Seek(25 * (DRP - 1), SeekOrigin.Begin);
                        logSession.WriteLine(tranCode + " " + tCode);
                        logSession.WriteLine(">> "+ inputFile.ReadLine());
                        logSession.WriteLine("[# of nodes read: " + index.NodeCount.ToString() + "]");
                    }
                }

                index.FinishUp();
                inputFile.Close();
                tranInputFile.Close();

            }

            logSession.Close();
        }
Example #14
0
        static String ReadOutput(StreamReader reader, bool print = true)
        {
            StringBuilder str = new StringBuilder();
            reader.DiscardBufferedData();
            while (reader.Peek() != -1)
            {
                str.Append((char)reader.Read());
            }
            str.Append("\n");

            if(print)
                Console.WriteLine("engine << " + str.ToString());
            
            return str.ToString().Trim();
        }
Example #15
0
 public IEnumerable<string> ReadLines(FileInfo sourceFile)
 {
     using (var reader = new StreamReader(sourceFile.FullName))
     {
         while (true)
         {
             if (reader.EndOfStream)
             {
                 reader.BaseStream.Position = 0;
                 reader.DiscardBufferedData();
             }
             yield return reader.ReadLine();
         }
     }
 }
Example #16
0
        private string GetJsonPart(Stream stream)
        {
            stream.Seek(JsonBegin, SeekOrigin.Begin);

            const int searchStringLength = 6;

            using (var streamReader = new StreamReader(stream))
            {
                var buffer = new char[searchStringLength];

                int charsCount = 0;

                bool jsonEndIsFound = false;

                while (!streamReader.EndOfStream)
                {
                    streamReader.ReadBlock(buffer, 0, searchStringLength);

                    if (new string(buffer).Equals("}}star"))
                    {
                        jsonEndIsFound = true;
                        break;
                    }

                    streamReader.BaseStream.Seek(JsonBegin + charsCount, SeekOrigin.Begin);

                    charsCount++;

                    streamReader.DiscardBufferedData();
                }

                if (!jsonEndIsFound)
                {
                    throw new NotSupportedException();
                }

                stream.Seek(JsonBegin, SeekOrigin.Begin);

                var bytesLengths = (charsCount * 2);
                var jsonBytes = new byte[bytesLengths];
                stream.Read(jsonBytes, 0, bytesLengths);

                var str = Encoding.UTF8.GetString(jsonBytes);

                return str.Substring(0, str.LastIndexOf("}}star", StringComparison.InvariantCulture) + 2);
            }
        }
Example #17
0
 private string FindTo(StreamReader reader, long startPos, long endPos)
 {
     long pos = FindStringInStream(reader, "<To>", startPos, endPos);
     if (pos == -1)
         return string.Empty;
     reader.BaseStream.Seek(pos, SeekOrigin.Begin);
     reader.DiscardBufferedData();
     char[] buffer = new char[4096];
     int charsRead = reader.ReadBlock(buffer, 0, buffer.Length);
     string str = new string(buffer, 0, charsRead);
     Match m = Regex.Match(str, @".*?<To>(.*?)(</).*", RegexOptions.IgnoreCase);
     if (m != null && m.Success)
     {
         return m.Groups[1].Value;
     }
     return string.Empty;
 }
 protected void InternalParseDumpedFile(string path, string infoSectionName)
 {
     var infoSection = "[" + infoSectionName + "]\r\n";
     var digest = "";
     var timeStamp = PcdbFile.InvalidDateTime;
     using (var reader = new StreamReader(path, Encoding.Default))
     {
         var pos = StreamScanner.FindString(reader.BaseStream, reader.CurrentEncoding, infoSection);
         if (pos == -1)
             return;
         reader.DiscardBufferedData();
         reader.BaseStream.Seek(pos, SeekOrigin.Begin);
         reader.ReadLine();
         while (!reader.EndOfStream)
         {
             if (Cancelled)
                 break;
             var buf = reader.ReadLine();
             var entry = IniFile.ExtractKeyValuePair(buf, false);
             switch (entry.Key)
             {
             case "creation_date":
                 timeStamp = Utils.StrToDateTime(entry.Value, Utils.DateTimePatternCfg);
                 continue;
             case "player_digest":
                 digest = entry.Value;
                 if (string.IsNullOrEmpty(digest))
                     return;
                 OnFoundData(DatabaseTableId.Hash);
                 continue;
             case "player_name":
             {
                 var name = entry.Value;
                 if (!string.IsNullOrEmpty(digest))
                 {
                     Database.InsertHash(digest);
                     OnFoundData(DatabaseTableId.Name);
                     if (!string.IsNullOrEmpty(name))
                         Database.InsertName(digest, name, timeStamp);
                 }
                 return;
             }
             }
         }
     }
 }
Example #19
0
        private static void convertToMethod(int spaceCount, StringBuilder methodBuilder, StreamReader reader, ClassTemplate meta)
        {
            if (methodBuilder == null || reader == null || meta == null)
                return;

            //文件流回到开始的位置
            reader.DiscardBufferedData();
            reader.BaseStream.Seek(0, SeekOrigin.Begin);
            reader.BaseStream.Position = 0;

            string line = reader.ReadLine();
            while (line != null)
            {
                line = findAndReplace(line, "%field_type%", meta.Field_type);
                line = findAndReplace(line, "%field_name%", meta.Field_name);
                line = findAndReplace(line, "%Field_name%", meta.Upper_field_name);
                methodBuilder.Append(getDesignatedSpace(spaceCount)).Append(line).Append("\r\n");
                line = reader.ReadLine();
            }
        }
Example #20
0
 private string FindMethod(StreamReader reader, long startPos, long endPos)
 {
     long pos = FindStringInStream(reader, "Body", startPos, endPos);
     if (pos == -1)
         return string.Empty;
     reader.BaseStream.Seek(pos, SeekOrigin.Begin);
     reader.DiscardBufferedData();
     char[] buffer = new char[200];
     int charsRead = reader.ReadBlock(buffer, 0, buffer.Length);
     string str = new string(buffer, 0, charsRead);
     Match m = Regex.Match(str, @".*?<(.*?)( |>).*", RegexOptions.IgnoreCase);
     if (m != null && m.Success)
     {
         string method = m.Groups[1].Value;
         if (method.Contains(":"))
         {
             method = method.Split(':')[1];
         }
         return method;
     }
     return string.Empty;
 }
Example #21
0
		public void FillBuffer(string filePath, int linesToRead)
		{
			using (var reader = new StreamReader(filePath))
			{
				reader.BaseStream.Seek(Math.Max(0, reader.BaseStream.Length - (512 * (linesToRead + 1))), SeekOrigin.Begin);
				reader.DiscardBufferedData();

				var rawLines = new List<string>();
				while (!reader.EndOfStream)
				{
					rawLines.Add(reader.ReadLine());
				}
				for (int i = Math.Max(0, rawLines.Count - linesToRead); i < rawLines.Count; i++)
				{
					var cl = this.Parse(rawLines[i]);
					if (cl != null)
					{
						this.Buffer.Enqueue(cl);
					}
				}
			}
		}
Example #22
0
		void ReadStrings ()
		{
			int i;

			num_strings = Util.ReadWord (stream);

			int[] offsets = new int[num_strings];

			for (i = 0; i < num_strings; i ++) {
				offsets[i] = Util.ReadWord (stream);
			}

			StreamReader tr = new StreamReader (stream);
			strings = new string[num_strings];

			for (i = 0; i < num_strings; i++) {
				if (tr.BaseStream.Position != offsets[i]) {
					tr.BaseStream.Seek (offsets[i], SeekOrigin.Begin);
					tr.DiscardBufferedData ();
				}

				strings[i] = Util.ReadUntilNull (tr);
			}
		}
Example #23
0
        static bool VerifyZipAndRegion()
        {
            //////////////////////////////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////// INITIALIZING VARIABLES
            //////////////////////////////////////////////////////////////////////////////////////////
            string[] aryTableParsedLine;
            string[] aryDataParsedLine;
            string strDataLine;
            string strTableLine;
            string strEditedDataFile = strInputDataName.ToUpper().Replace(".CSV", "_EDITED.CSV");
            string strCurrentZip;
            string strDataZipAndRegion;
            string strTableZipAndRegion;
            int iZipFieldIndex = 0;
            int iDataFields;
            bool bolFoundRegionMatch;
            int iInputRecords;
            int iEditedRecords;
            int iMismatchRecords;
            bool bolZipFieldFound = false;
            strRegionErrorsRemoved = strWorkingJobFolder + strJobNumber + " - Region Mismatches Removed.csv";

            StreamReader streamInitialFileScan = new StreamReader(strInputDataName);
            StreamReader streamTableFile = new StreamReader(strZipToRegionTable);
            StreamWriter streamEditedDataFile = new StreamWriter(strEditedDataFile);
            StreamWriter streamRegionMismatches = new StreamWriter(strRegionErrorsRemoved);

            TextFieldParser parseDataFile = new TextFieldParser(strInputDataName);
            parseDataFile.TextFieldType = FieldType.Delimited;
            parseDataFile.SetDelimiters(",");

            try
            {
                //////////////////////////////////////////////////////////////////////////////////////////
                ////////////////////////// DETERMINING WHICH FIELD IN THE INPUT DATA CONTAINS THE ZIP CODE
                //////////////////////////////////////////////////////////////////////////////////////////
                strDataLine = streamInitialFileScan.ReadLine();
                aryDataParsedLine = strDataLine.Split(',');
                iDataFields = aryDataParsedLine.Length;

                for (int j = 0; j < iDataFields; j++)
                {
                    if (aryDataParsedLine[j].ToString().ToUpper().Contains("ZIP"))
                    {
                        bolZipFieldFound = true;
                        streamEditedDataFile.WriteLine(strDataLine);
                        iZipFieldIndex = j;

                        break;
                    }
                }

                streamInitialFileScan.Close();
                streamInitialFileScan.Dispose();

                // Verifying that a zip code field exists in the input data file.
                if (!bolZipFieldFound)
                {
                    LogFile("A Zip field is not included in the input data file.", true);
                    return false;
                }

                //////////////////////////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////// TESTING EACH RECORD AGAINST THE ZIP-REGION TABLE
                //////////////////////////////////////////////////////////////////////////////////////////
                while (!parseDataFile.EndOfData)
                {
                    bolFoundRegionMatch = false;

                    strDataLine = parseDataFile.PeekChars(Int32.MaxValue);
                    aryDataParsedLine = parseDataFile.ReadFields();

                    // Capturing the zip and region combination from the current record.
                    strCurrentZip = aryDataParsedLine[iZipFieldIndex].ToString().Trim();

                    if (strCurrentZip.Length > 5)
                    {
                        strCurrentZip = strCurrentZip.Substring(0,5);
                    }

                    strDataZipAndRegion = strCurrentZip + strRegionCode;

                    // Looping through the Zip and Region Lookup Table to see if a zip is within a valid region.
                    while (!streamTableFile.EndOfStream)
                    {
                        strTableLine = streamTableFile.ReadLine();
                        aryTableParsedLine = strTableLine.Split(',');

                        strTableZipAndRegion = aryTableParsedLine[0].ToString() + aryTableParsedLine[2].ToString().ToUpper().Trim();

                        if (strDataZipAndRegion == strTableZipAndRegion)
                        {
                            bolFoundRegionMatch = true;

                            break;
                        }
                    }

                    if (bolFoundRegionMatch)
                    {
                        streamEditedDataFile.WriteLine(strDataLine);
                    }
                    else
                    {
                        streamRegionMismatches.WriteLine(strDataLine);
                    }

                    streamTableFile.DiscardBufferedData();
                    streamTableFile.BaseStream.Position = 0;
                }
            }
            catch (Exception exception)
            {
                LogFile(exception.ToString(), true);
                return false;
            }
            finally
            {
                streamEditedDataFile.Close();
                streamEditedDataFile.Dispose();
                streamTableFile.Close();
                streamTableFile.Dispose();
                streamRegionMismatches.Close();
                streamRegionMismatches.Dispose();
                parseDataFile.Close();
                parseDataFile.Dispose();
            }

            //////////////////////////////////////////////////////////////////////////////////////////
            /////////////////////////////////// DETERMINING IF THE HIGHMARK THRESHOLD HAS BEEN REACHED
            //////////////////////////////////////////////////////////////////////////////////////////
            try
            {
                // Calculating total number of input records.
                iInputRecords = File.ReadAllLines(strInputDataName).Length - 1;

                // Calculating total number of edited records.
                iEditedRecords = File.ReadAllLines(strEditedDataFile).Length - 1;

                // Calculating total number of mismatch records.
                iMismatchRecords = File.ReadAllLines(strRegionErrorsRemoved).Length - 1;

                if ((((decimal)iEditedRecords / (decimal)iInputRecords) * 100) <= iZipToRegionMismatchThreshold)
                {
                    bolRegionMismatchThresholdReached = true;

                    SendEmail("HIGHMARK");
                    LogFile("At least " + (100 - iZipToRegionMismatchThreshold).ToString() + "% of records submitted for processing were removed as Region-Zip mismatches.", true);
                    return false;
                }
                else
                {
                    if (iMismatchRecords > 1)
                    {
                        SendEmail("HIGHMARK");
                    }
                }
            }
            catch (Exception exception)
            {
                LogFile(exception.ToString(), true);
                return false;
            }

            strInputDataName = strEditedDataFile;
            return true;
        }
Example #24
0
        public override void Initialize()
        {
            if (String.IsNullOrEmpty(_fileToWatch))
                return;

            _fileReader =
                new StreamReader(new FileStream(_fileToWatch, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

            string path = Path.GetDirectoryName(_fileToWatch);
            _filename = Path.GetFileName(_fileToWatch);
            _fileWatcher = new FileSystemWatcher(path, _filename)
                               {NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size};
            _fileWatcher.Changed += OnFileChanged;
            _fileWatcher.EnableRaisingEvents = true;

            ComputeFullLoggerName();

            if (ReadHeaderFromFile)
                AutoConfigureHeader();

            if (!_showFromBeginning)
            {
                _fileReader.BaseStream.Seek(0, SeekOrigin.End);
                _fileReader.DiscardBufferedData();
            }
        }
Example #25
0
 private string ReadLine(StreamReader sr, int i)
 {
     var filePos = sourceFileLinePositions[i];
     if (filePos < 0)
         return "";
     fs.Seek(filePos, SeekOrigin.Begin);
     sr.DiscardBufferedData();
     var line = sr.ReadLine();
     return line;
 }
Example #26
0
        public static bool IsBinaryFile(FileStream F)
        {
            F.Seek(0, SeekOrigin.Begin);

            //First see if the file begins with any known Unicode byte order marks.
            //If so, then it is a text file.  Use a StreamReader instance to do the
            //auto-detection logic.
            //
            //NOTE: I'm not disposing of the StreamReader because that closes the
            //associated Stream.  The caller opened the file stream, so they should
            //be the one to close it.
            StreamReader Reader = new StreamReader(F, Encoding.Default, true);
            Reader.Read(); //We have to force a Read for it to auto-detect.
            if (Reader.CurrentEncoding != Encoding.Default)
            {
                return false;
            }
            Reader.DiscardBufferedData();
            Reader = null;

            //Since the type was Default encoding, that means there were no byte-order
            //marks to indicate its type.  So we have to scan.  If we find a NULL
            //character in the stream, that means it's a binary file.
            F.Seek(0, SeekOrigin.Begin);
            int i;
            while ((i = F.ReadByte()) > -1)
            {
                if (i == 0)
                {
                    return true;
                }
            }

            return false;
        }
Example #27
0
        private void frmLogin_Load(object sender, EventArgs e)
        {
            //READ FILE
            //local variables
            string[] productData;
            string[] branchData;
            string[] categoryData;

            //set up StreamReader
            StreamReader reader = new StreamReader("argus-BIG.txt");

            //make reader start at beginning of file
            reader.DiscardBufferedData();
            reader.BaseStream.Seek(0, SeekOrigin.Begin);
            reader.BaseStream.Position = 0;

            while (!reader.EndOfStream)
            {
                //create array to hold data values
                branchData = new string[11];

                //get 11 lines of branch data file
                for (int i = 0; i < 11; i++)
                {
                    branchData[i] = reader.ReadLine();
                }

                //new instance of Branch Class
                Branch tempBranch = new Branch(branchData[0], branchData[1], branchData[2],
                                                branchData[3], branchData[4], branchData[5],
                                                    branchData[6], branchData[7], branchData[8],
                                                        branchData[9], Convert.ToInt32(branchData[10]));

                //add branch to main arrayList
                tempBranch.addBranchToMainArgus(tempBranch);

                for (int i = 0; i < Convert.ToInt32(tempBranch.getNoCategories()); i++)
                {
                    //create array to hold data values
                    categoryData = new string[3];

                    //get 3 lines of category data file
                    for (int j = 0; j < 3; j++)
                    {
                        categoryData[j] = reader.ReadLine();
                    }

                    //new instance of Category Class
                    Category tempCategory = new Category(Convert.ToInt32(categoryData[0]), categoryData[1],
                                                            Convert.ToInt32(categoryData[2]));

                    //add category to Categories in branch arrayList
                    tempBranch.addCategoryToBranch(tempCategory);

                    for (int j = 0; j < Convert.ToInt32(tempCategory.getNoProduct()); j++)
                    {
                        //create array to hold data values
                        productData = new string[6];

                        //get 6 lines of category data file
                        for (int k = 0; k < 6; k++)
                        {
                            productData[k] = reader.ReadLine();
                        }

                        //new instance of Product Class
                        Product tempProduct = new Product(Convert.ToInt32(productData[0]), productData[1], productData[2],
                                                            productData[3], Convert.ToSingle(productData[4]), Convert.ToInt32(productData[5]));

                        //add product to productsincategory arraylist
                        tempCategory.addProduct(tempProduct);
                    }
                }
            }
        }
Example #28
0
        private void TrimLog (FileInfo logFile)
        {
            // Check if we need to trim the log file:
            if (logFile.Exists && logFile.Length >= FileTrimThresholdSize) {
                var tmpFile = new FileInfo (Path.Combine (logDir, FileTempName));
                try {
                    if (tmpFile.Exists) {
                        tmpFile.Delete ();
                    }
                    File.Move (logFile.FullName, tmpFile.FullName);
                    logFile.Refresh ();
                    tmpFile.Refresh ();

                    // Copy data over to new file
                    using (var tmpReader = new StreamReader (tmpFile.FullName, Encoding.UTF8))
                    using (var logWriter = new StreamWriter (logFile.FullName, false, Encoding.UTF8)) {
                        // Skip to where we can start copying
                        tmpReader.BaseStream.Seek (-FileTrimTargetSize, SeekOrigin.End);
                        tmpReader.DiscardBufferedData ();
                        tmpReader.ReadLine ();

                        string line;
                        while ((line = tmpReader.ReadLine ()) != null) {
                            logWriter.WriteLine (line);
                        }
                    }
                } catch (SystemException ex) {
                    Console.WriteLine ("Failed to trim log file.");
                    Console.WriteLine (ex);

                    // Make sure that the log file is deleted so we can start a new one
                    try {
                        logFile.Delete ();
                    } catch (SystemException ex2) {
                        Console.WriteLine ("Failed to clean up log file.");
                        Console.WriteLine (ex2);
                    }
                } finally {
                    try {
                        tmpFile.Delete ();
                    } catch (SystemException ex) {
                        Console.WriteLine ("Failed to clean up temporary log file.");
                        Console.WriteLine (ex);
                    }
                }
            }
        }
Example #29
0
 protected override MemoryStream getStreamDataPortion(MemoryStream data )
 {
     StreamReader reader = new StreamReader(data, ASCIIEncoding.ASCII);
     String line = reader.ReadLine();
     if ( line.StartsWith("*") ) {
         int size = this.parseInteger((line.Substring(line.LastIndexOf('{'))).Trim(new Char[]{'{','}'}));
         if ( size>0 ) {
             int offset = ASCIIEncoding.ASCII.GetByteCount(line + "\r\n");
             reader.DiscardBufferedData();
             reader=null;
             data.Seek(offset, SeekOrigin.Begin);
             data.SetLength(offset + size);
         }
     }
     return data;
 }
Example #30
0
        public static string binSearchSemCor(string uniqueid, string searchKey,StreamReader fp)
        {
            int c,n;
            long top,bot,mid,diff;
            string line,key;
            searchKey = searchKey.ToLower(); // for some reason some WordNet words are stored with a capitalised first letter, whilst all words in the sense index are lowercase
            diff = 666; // ???
            line = "";
            bot = fp.BaseStream.Seek(0,SeekOrigin.End);
            top = 0;
            mid = (bot-top)/2;
            do
            {
                fp.DiscardBufferedData();
                fp.BaseStream.Position = mid-1;

                if (mid!=1)
                    fp.ReadLine();
            //					while ((c=fp.Read())!='\n' && c!=-1)
            //						;
                line = fp.ReadLine();
                if (line==null)
                    return null;
                n = line.IndexOf('%');
                key = line.Substring(0,n);
               				int co; // compareordinal result

                co = String.CompareOrdinal(key, searchKey);

                if (co<0)
                {
                    // key is alphabetically less than the search key
                    top = mid;
                    diff = (bot - top)/2;
                    mid = top + diff;
                }
                if (co>0)
                {
                    // key is alphabetically greater than the search key
                    bot = mid;
                    diff = (bot - top)/2;
                    mid = top + diff;
                }
            } while (key!=searchKey && diff!=0);

            // we have found an exact match
            if (line.IndexOf(uniqueid, 0) > 0)
                return line;

            // set the search down the list and work up
            fp.DiscardBufferedData();
            fp.BaseStream.Position -= 4000;
            //fp.BaseStream.Seek((long)(-1000), SeekOrigin.Current);

            // move down until we find the first matching key
            do
            {
                line = fp.ReadLine();
                n = line.IndexOf('%');
                key = "";

                if(n > 0)
                    key = line.Substring(0,n);
            } while(key != searchKey);

            // scroll through matching words until the exact identifier is found
            do
            {
                if(line.IndexOf(uniqueid, 0) > 0)
                    return line;

                line = fp.ReadLine();
                n = line.IndexOf('%');
                key = line.Substring(0,n);
            } while(key == searchKey);

            return null;
        }