DiscardBufferedData() public method

public DiscardBufferedData ( ) : void
return void
Beispiel #1
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();
        }
Beispiel #2
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;
        }
        //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;
        }
Beispiel #4
0
 public EdiStream(Stream ediStream)
 {
     _streamReader = new StreamReader(ediStream);
     _interchangeContext = new InterchangeContext(_streamReader);
     ediStream.Position = 0;
     _streamReader.DiscardBufferedData();
 }
Beispiel #5
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();
        }
Beispiel #6
0
        private List <string> ReadColumns(ref System.IO.StreamReader file, string FirstLine)
        {
            List <string> col  = new List <string>();
            string        line = string.Empty;

            string[] elements;
            int      Index = 0;

            while ((line = file.ReadLine()) != null)
            {
                if ((line.Equals(FirstLine)))
                {
                    continue;
                }
                if ((line.Equals(Environment.NewLine)) || (line.Equals(string.Empty)))
                {
                    break;
                }
                elements = line.Split('=');
                col.Add(elements[0].Trim());
                Index++;
            }
            file.BaseStream.Position = 0;
            file.DiscardBufferedData();
            return(col);
        }
        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() );
            }
        }
Beispiel #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");

            }
        }
Beispiel #9
0
        }  // end closeFile

        // Rewind the input file
        public void rewindFile()
        {
            recordReadCount = 0;
            currentFileSR   = new System.IO.StreamReader(currentFilePath);
            currentFileSR.DiscardBufferedData();
            currentFileSR.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
        }  // end rewindFile
Beispiel #10
0
 public EdiStream(Stream ediStream, string definitionsAssemblyName = null)
 {
     _streamReader = new StreamReader(ediStream);
     _interchangeContext = new InterchangeContext(_streamReader, definitionsAssemblyName);
     ediStream.Position = 0;
     _streamReader.DiscardBufferedData();
 }
        private async System.Threading.Tasks.Task GetDIVersions()
        {
            string selectedItem = DriveBox.SelectedItem.ToString();

            if (File.Exists(selectedItem + "CURRENT.UF2"))
            {
                StreamReader currentUF2 = new System.IO.StreamReader(selectedItem + "CURRENT.UF2");

                string lineFW;
                int    x = 0;
                while ((lineFW = currentUF2.ReadLine()) != null)
                {
                    if (lineFW.Contains("DI_FW_"))
                    {
                        var    regex   = new Regex(@"DI_FW_\d*\.\d*");
                        string version = (regex.Match(lineFW).ToString()).Replace("DI_FW_", "");
                        FirmwareVersionLabel.Text = "v" + version;
                        OutputBox.Content        += "\nFound firmware version on DragonInjector (" + selectedItem.Replace("\\", "") + "): v" + version;
                        OutputBox.ScrollToBottom();
                        x++;
                    }
                }
                if (x < 1)
                {
                    FirmwareVersionLabel.Text = "Custom";
                }

                currentUF2.DiscardBufferedData();
                currentUF2.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                string lineBL;
                int    y = 0;
                while ((lineBL = currentUF2.ReadLine()) != null)
                {
                    if (lineBL.Contains("DI_BL_"))
                    {
                        var    regex   = new Regex(@"DI_BL_\d*\.\d*");
                        string version = (regex.Match(lineBL).ToString()).Replace("DI_BL_", "");
                        BootloaderVersionLabel.Text = "v" + version;
                        OutputBox.Content          += "\nFound bootloader version on DragonInjector (" + selectedItem.Replace("\\", "") + "): v" + version;
                        OutputBox.ScrollToBottom();
                        y++;
                    }
                }
                if (y < 1)
                {
                    BootloaderVersionLabel.Text = "Custom";
                }
                currentUF2.Dispose();
            }
            else
            {
                FirmwareVersionLabel.Text = "UNKNOWN";
                OutputBox.Content        += "\n!Couldn't find firmware version on DragonInjector";
                OutputBox.ScrollToBottom();
                BootloaderVersionLabel.Text = "UNKNOWN";
                OutputBox.Content          += "\n!Couldn't find bootloader version on DragonInjector";
                OutputBox.ScrollToBottom();
            }
        }
 public TilesetTableTest()
 {
     var tilesetTableMemoryStream = FileStreams.TilesetTableStream();
     var tilesetTableStreamReader = new StreamReader(tilesetTableMemoryStream);
     tilesetTableStreamReader.DiscardBufferedData();
     tilesetTableMemoryStream.Position = 0;
     var tilesetTable = new TilesetTable(null, tilesetTableStreamReader);
 }
Beispiel #13
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 !");
            }
        }
Beispiel #14
0
        public void restoreConfigMinMaxGetValuesCsharp()
        {
            if (restore_filename != null)
            {
                // fp_restore rewinded in finding max_index
                int    idx;
                double fmin, fmax;
                string restore_line;

                if (fp_restore.Read() == 'y')
                {
                    fp_restore.ReadLine();                              // pass the '\n' after 'y'
                    restore_line = fp_restore.ReadLine();
                    string [] restore_line_ar = restore_line.Split(',');
                    y_lower = double.Parse(restore_line_ar[0]);
                    y_upper = double.Parse(restore_line_ar[1]);

                    restore_line    = fp_restore.ReadLine();
                    restore_line_ar = restore_line.Split(',');
                    y_min           = double.Parse(restore_line_ar[0]);
                    y_max           = double.Parse(restore_line_ar[1]);
                    y_scaling       = true;
                }
                else
                {
                    fp_restore.BaseStream.Position = 0;
                    fp_restore.DiscardBufferedData();
                }

                if (fp_restore.Read() == 'x')
                {
                    fp_restore.ReadLine();              // pass the '\n' after 'x'
                    restore_line = fp_restore.ReadLine();
                    string[] restore_line_ar = restore_line.Split(',');
                    lower = double.Parse(restore_line_ar[0]);
                    upper = double.Parse(restore_line_ar[1]);

                    restore_line    = null;
                    restore_line_ar = null;
                    while ((restore_line = fp_restore.ReadLine()) != null)
                    {
                        restore_line_ar = restore_line.Split(',');
                        idx             = int.Parse(restore_line_ar[0]);
                        fmin            = double.Parse(restore_line_ar[1]);
                        fmax            = double.Parse(restore_line_ar[2]);
                        if (idx <= max_index) // this will ignore index 204801 if the max is 204800
                        {
                            feature_min[idx] = fmin;
                            feature_max[idx] = fmax;
                        }
                    }
                }
                fp_restore.Close();
            }
        }
 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;
 }
Beispiel #16
0
 private void Reset(object sender, RoutedEventArgs e)
 {
     streamReader.DiscardBufferedData();
     streamReader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
     myCanvas2.Children.Clear();
     for (int i = 0; i < 10; i++)
     {
         word[i] = null;
         line    = null;
     }
 }
Beispiel #17
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();
        }
Beispiel #18
0
    /// <summary>
    /// Creates a new Level with this Level's starting settings.
    /// Returns null if there was a problem creating the Level.
    /// </summary>
    /// <returns>A Level with this Level's starting settings or null.</returns>
    public Level RestartLevel()
    {
        Level lvl;

        //if this is not a replay
        if (updateFile == null)
        {
            //get the same number Level
            lvl = GetLevel(levelNumber);

            if (lvl != null)
            {
                //create the Level using the same settings
                lvl.Create(thePlayers.Length, theDifficulty, randomSeed, thePvp);

                //copy the Item's the Players had at the begining of the Level
                for (int i = 0; i < thePlayers.Length; i++)
                {
                    for (int j = 0; j < thePlayers[i].items.Length; j++)
                    {
                        if (initialPlayers[i].items[j] != null)
                        {
                            initialPlayers[i].items[j].Pickup(lvl.thePlayers[i], j);
                            lvl.theNonInteractives.AddLast(lvl.thePlayers[i].items[j]);
                            theNonInteractives.Remove(lvl.thePlayers[i].items[j]);
                        }
                    }
                    lvl.initialPlayers[i] = lvl.thePlayers[i].Clone();
                }

                //destroy this Level
                ClearLevel();
                Destroy(this.gameObject);
            }
        }
        //if this is a replay
        else
        {
            //set the replay file to the begining and reload the replay
            updateFile.DiscardBufferedData();
            updateFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            lvl = LoadReplay(updateFile);

            //if the replay was loaded successfuly, then destroy this Level
            if (lvl != null)
            {
                updateFile = null;
                ClearLevel();
                Destroy(this.gameObject);
            }
        }

        return(lvl);
    }
Beispiel #19
0
        private string ReadSparClass(ref System.IO.StreamReader file)
        {
            string line = string.Empty;

            if ((line = file.ReadLine()) != null)
            {
                file.BaseStream.Position = 0;
                file.DiscardBufferedData();
                return(line);
            }
            return(line);
        }
Beispiel #20
0
 /*
  * transmit log file, this is called when   user clicks on the transfer log file button
  * it reads the file selected and starts transmitting the log file with the command sendNextLogFile
  */
 private void trLogFile(object sender, EventArgs e)
 {
     if (readFile == null)
     {
         txtGatewayLog.Text += "No file selected!\n";
         return;
     }
     readFile.DiscardBufferedData();
     readFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
     sendingLog = true;
     readFile.ReadLine();
     sendNextLogFile();
 }
        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();
        }
Beispiel #22
0
        static void mostrarTokens(TinyLexer lexer, System.IO.StreamReader input)
        {
            Console.WriteLine("####### Inicio del análisis léxico #######");
            Symbol symbol;

            while ((symbol = lexer.next_token()).sym != TokenDef.EOF)
            {
                Utilidades.dumpToken(System.Console.Out, symbol);
            }

            input.BaseStream.Position = 0;
            input.DiscardBufferedData();
            Console.WriteLine("####### Fin del análisis léxico #######");
        }
Beispiel #23
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();
        }
Beispiel #24
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();
         }
     }
 }
Beispiel #25
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);
            }
        }
Beispiel #26
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;
             }
             }
         }
     }
 }
Beispiel #28
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();
            }
        }
Beispiel #29
0
    public static Dictionary <string, string>[] ReadPatientFile(int tam)
    {
        System.IO.StreamReader sr = new System.IO.StreamReader(GlobalVar.PatientsFile);
        String oneLine            = sr.ReadLine();
        int    i = 0;

        //recorro el fichero para ver el número de filas (pacientes) que contiene
        while (oneLine != null)
        {
            oneLine = sr.ReadLine();
            i++;
        }

        sr.DiscardBufferedData();
        sr.BaseStream.Seek(0, SeekOrigin.Begin);

        //con el número de pacientes del fichero, declaramos el tamaño de la matriz de dictionary
        Dictionary <string, string>[] data_patient = new Dictionary <string, string> [i];

        oneLine = sr.ReadLine();
        i       = 0;
        while (oneLine != null)
        {
            //MessageBox.Show(oneLine);
            string[] fields = oneLine.Split('|');
            data_patient[i] = new Dictionary <string, string>();
            data_patient[i].Add("task_id", fields[0]);
            data_patient[i].Add("admission_id", fields[1]);
            data_patient[i].Add("name", fields[2]);
            data_patient[i].Add("surname", fields[3]);
            data_patient[i].Add("gender", fields[4]);
            data_patient[i].Add("bdate", fields[5]);
            data_patient[i].Add("cip", fields[6]);
            oneLine = sr.ReadLine();
            i++;
        }

        sr.Close();
        return(data_patient);
    }
Beispiel #30
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;
 }
Beispiel #31
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);
					}
				}
			}
		}
Beispiel #32
0
        public override void CicloPrincipale()
        {
            int[] bufferCorrente = new int[DimensioneBuffer];
            int   cursore        = 0;

            // Leggo le righe una ad una
            System.IO.StreamReader file = new System.IO.StreamReader(_percorsoFile);
            do
            {
                string rigaCorrente;

                while ((rigaCorrente = file.ReadLine()) != null)
                {
                    if (rigaCorrente != null && rigaCorrente.Length > 0)
                    {
                        int valoreCorrente = Convert.ToInt32(rigaCorrente);
                        bufferCorrente[cursore] = valoreCorrente;
                        cursore++;

                        // Se il buffer è stato riempito, lo notifico alla sorgente
                        if (cursore >= DimensioneBuffer)
                        {
                            NotificaDatiDisponibili(bufferCorrente);
                            cursore = 0;
                        }

                        // Sleep per un piccolo periodo
                        System.Threading.Thread.Sleep(TempoSleep);
                    }
                }

                // Ritorno all'inizio del file per ricominciare la lettura
                file.DiscardBufferedData();
                file.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            } while (!_dovrebbeFermarsi);

            file.Close();
        }
Beispiel #33
0
        //find max_index from the restore file
        public void restoreCofingFileGetMaxIndexCsharp()
        {
            fp_restore = null;
            if (restore_filename != null)
            {
                int idx, c;

                try
                {
                    fp_restore = new StreamReader(restore_filename);
                }
                catch (System.Exception e)
                {
                    System.Console.Error.WriteLine("can't open file " + restore_filename);
                    //Environment.Exit(1);
                }
                if (fp_restore.Read() == 'y')
                {
                    fp_restore.ReadLine();
                    fp_restore.ReadLine();
                    fp_restore.ReadLine();
                }
                fp_restore.ReadLine();
                fp_restore.ReadLine();

                string restore_line = null;
                while ((restore_line = fp_restore.ReadLine()) != null)
                {
                    idx       = int.Parse(restore_line.Split(',')[0]);
                    max_index = System.Math.Max(max_index, idx);
                }

                //rewind stream.
                fp_restore.BaseStream.Position = 0;
                fp_restore.DiscardBufferedData();
            }
        }
Beispiel #34
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);
			}
		}
Beispiel #35
0
        private List <List <string> > ReadRows(ref System.IO.StreamReader file, string FirstLine)
        {
            List <List <string> > Rows    = new List <List <string> >();
            List <string>         RowData = new List <string>();
            string line = string.Empty;

            while ((line = file.ReadLine()) != null)
            {
                string[] elements;
                if ((line.Equals(FirstLine)))
                {
                    continue;
                }
                if ((line.Equals(Environment.NewLine)) || (line.Equals(string.Empty)))
                {
                    Rows.Add(RowData);
                    RowData = new List <string>();
                }
                else if (line.Contains('='))
                {
                    elements = line.Split('=');
                    RowData.Add(elements[1].Trim());
                }
                else
                {
                    // Do nothing
                }
            }
            if (file.EndOfStream)
            {
                Rows.Add(RowData);
            }
            file.BaseStream.Position = 0;
            file.DiscardBufferedData();
            return(Rows);
        }
Beispiel #36
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();
            }
        }
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Console.WriteLine(args);
                for (int id = 0; id < args.Length; id++)
                {
                    Console.WriteLine(args[id]);
                    if ((File.Exists(args[id])) && (args[id].Contains(".pit")))
                    {
                        // File paths
                        string homedir   = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                        string filename  = args[id];
                        string looklist  = homedir + "\\look_list.csv";
                        string filedest1 = "header.txt";
                        string filedest2 = "base_look.txt";
                        string filedest3 = "def_look.txt";
                        string filedest4 = "trailer.txt";

                        // Initialisation of global parameters
                        int  lookcnt     = 1;
                        int  baselook_id = 0;
                        bool isheader    = true;
                        bool islook      = false;
                        bool isbaselook  = true;
                        bool istrailer   = false;

                        string[] look_name;
                        string[] texture_tag;
                        string[] texture_path;

                        // Read and store the look list
                        using (var fs = File.OpenRead(looklist))
                            using (var reader = new StreamReader(fs))
                            {
                                List <string> listA = new List <string>();
                                List <string> listB = new List <string>();
                                List <string> listC = new List <string>();
                                while (!reader.EndOfStream)
                                {
                                    var line   = reader.ReadLine();
                                    var values = line.Split(',');

                                    listA.Add(values[0]);
                                    listB.Add(values[1]);
                                    listC.Add(values[2]);
                                }
                                look_name    = listA.ToArray();
                                texture_tag  = listB.ToArray();
                                texture_path = listC.ToArray();
                                lookcnt      = look_name.Length;
                            }

                        // Initiate temporary files for the program to dump data
                        System.IO.StreamWriter filewrite1 = new System.IO.StreamWriter(filedest1);
                        System.IO.StreamWriter filewrite2 = new System.IO.StreamWriter(filedest2);
                        System.IO.StreamWriter filewrite3 = new System.IO.StreamWriter(filedest3);
                        System.IO.StreamWriter filewrite4 = new System.IO.StreamWriter(filedest4);

                        // Start work!
                        if (File.Exists(filename))
                        {
                            // Our strings that we use to read things from
                            string line;
                            string line2;

                            // Read the file and display it line by line.
                            System.IO.StreamReader file = new System.IO.StreamReader(filename);

                            while ((line = file.ReadLine()) != null)
                            {
                                // Screw comments!
                                if (line.StartsWith("#"))
                                {
                                    continue;
                                }

                                // Copy the header lines
                                while (isheader == true)
                                {
                                    string linetrim = NoWhiteSpace(line);
                                    // Let's check if we are still in the header range...
                                    if (linetrim.StartsWith("Look {"))
                                    {
                                        // kthnxbai
                                        isheader = false;
                                        islook   = true;
                                        filewrite1.Close();
                                        filewrite2.WriteLine(line);
                                        break;
                                    }
                                    // Change source name to identify this tool has processed this file...
                                    if (linetrim.StartsWith("Source"))
                                    {
                                        int denominator = line.IndexOf(":");
                                        filewrite1.WriteLine("{0}: \"PIT Look Addition Batch Tool by MandelSoft\"", line.Substring(0, denominator));
                                        //Console.WriteLine("{0} : \"PIT Look Addition Batch Tool by MandelSoft\"", line.Substring(0, denominator));
                                    }
                                    // Change the look count to match with the input look count of the look list...
                                    else if (linetrim.StartsWith("LookCount"))
                                    {
                                        int denominator = line.IndexOf(":");
                                        filewrite1.WriteLine("{0}: {1}", line.Substring(0, denominator), lookcnt);
                                        //Console.WriteLine("{0} : {1}", line.Substring(0, denominator), lookcnt);
                                    }
                                    // Nothing to see here, just copy-paste...
                                    else
                                    {
                                        filewrite1.WriteLine(line);
                                        //Console.WriteLine(line);
                                    }
                                    line = file.ReadLine();
                                }


                                while (islook == true)
                                {
                                    // We only want the first look, so if we have found it, we continue to the trailer.
                                    if (line.StartsWith("Variant {"))
                                    {
                                        // kthnxbai
                                        islook    = false;
                                        istrailer = true;
                                        break;
                                    }
                                    line = file.ReadLine();
                                    if (isbaselook == true)
                                    {
                                        if (line.StartsWith("Look {"))
                                        {
                                            // Well, we have reached the second look. We don't need you!
                                            isbaselook = false;
                                            // kthnxbai, we don't need to write to you anymore.
                                            filewrite2.Close();

                                            // Let's read the file we just created...
                                            System.IO.StreamReader file_baselook = new System.IO.StreamReader(filedest2);

                                            while ((line2 = file_baselook.ReadLine()) != null)
                                            {
                                                string linetrim = NoWhiteSpace(line2);
                                                // So, does this line contain the look name?
                                                if (linetrim.StartsWith("Name"))
                                                {
                                                    int    denominator   = line2.IndexOf(":");
                                                    int    name_endpoint = line2.Length - (denominator + 3);
                                                    string baselookname  = line2.Substring(denominator + 2, name_endpoint);
                                                    for (int i = 0; i < lookcnt; i++)
                                                    {
                                                        // Check if this look is in the look list...
                                                        if (baselookname.Contains(look_name[i]))
                                                        {
                                                            // Awesome! Let's write it down!
                                                            //Console.WriteLine("Look found: {0}", look_name[i]);
                                                            baselook_id = i;
                                                        }
                                                    }
                                                }
                                            }
                                            // OK, let's generate some new looks!
                                            for (int i = 0; i < lookcnt; i++)
                                            {
                                                // We start to read from the beginning...
                                                file_baselook.BaseStream.Position = 0;
                                                file_baselook.DiscardBufferedData();

                                                // Just continue minding your business until the file ends...
                                                while ((line2 = file_baselook.ReadLine()) != null)
                                                {
                                                    string linetrim = NoWhiteSpace(line2);
                                                    // Is this the look name?
                                                    if (linetrim.StartsWith("Name"))
                                                    {
                                                        // Let's rename it!
                                                        int denominator = line2.IndexOf(":");
                                                        filewrite3.WriteLine("{0}: \"{1}\"", line2.Substring(0, denominator), look_name[i]);
                                                        //Console.WriteLine("{0} : {1}", line2.Substring(0, denominator), look_name[i]);
                                                    }
                                                    // We're going to change the texture! Check if it's the texture we're looking for
                                                    else if (linetrim.StartsWith("Texture {"))
                                                    {
                                                        filewrite3.WriteLine(line2);
                                                        //Console.WriteLine(line2);
                                                        line2 = file_baselook.ReadLine();
                                                        filewrite3.WriteLine(line2);
                                                        //Console.WriteLine(line2);

                                                        // Is this the right texture tag? Or does it matter anyway?
                                                        if ((line2.Contains(texture_tag[i])) || (texture_tag[i] == "any"))
                                                        {
                                                            line2 = file_baselook.ReadLine();
                                                            int    denominator   = line2.IndexOf(":");
                                                            int    name_endpoint = line2.Length - (denominator + 3);
                                                            string texturename   = line2.Substring(denominator + 2, name_endpoint);
                                                            if (texturename.Contains(texture_path[baselook_id]))
                                                            {
                                                                // Awesome! We can replace the texture!
                                                                filewrite3.WriteLine("{0}: \"{1}\"", line2.Substring(0, denominator), texture_path[i]);
                                                                //Console.WriteLine("{0} : \"{1}\"", line2.Substring(0, denominator), texture_path[i]);
                                                            }
                                                            // These are not the textures are looking for...
                                                            else
                                                            {
                                                                filewrite3.WriteLine(line2);
                                                                //Console.WriteLine(line2);
                                                            }
                                                        }
                                                    }
                                                    // Nothing to see here, just copy-paste...
                                                    else
                                                    {
                                                        filewrite3.WriteLine(line2);
                                                        //Console.WriteLine(line2);
                                                    }
                                                }
                                            }
                                            // kthnxbai, we don't need to write to you anymore.
                                            filewrite3.Close();
                                            file_baselook.Close();
                                        }
                                        // Write down the base look!
                                        else
                                        {
                                            filewrite2.WriteLine(line);
                                        }
                                    }
                                }
                                // Let's write down the trailer lines.
                                while (istrailer == true)
                                {
                                    // Are we at the end of the file?
                                    if (line == null)
                                    {
                                        // kthnxbai
                                        islook    = false;
                                        istrailer = true;
                                        filewrite4.Close();
                                        break;
                                    }
                                    filewrite4.WriteLine(line);
                                    //Console.WriteLine(line);
                                    line = file.ReadLine();
                                }
                            }
                            // tl;dr, kthnxbai
                            file.Close();
                        }

                        // Entries, assemble!
                        using (var output = File.Create(filename))
                        {
                            foreach (var fileoutput in new[] { filedest1, filedest3, filedest4 })
                            {
                                using (var input = File.OpenRead(fileoutput))
                                {
                                    input.CopyTo(output);
                                }
                            }
                        }
                        // Hey, cleaning lady! We need to clean-up some files!
                        try
                        {
                            System.IO.File.Delete(filedest1);
                        }
                        catch (System.IO.IOException e)
                        {
                            Console.WriteLine(e.Message);
                            Console.ReadLine();
                            return;
                        }
                        try
                        {
                            System.IO.File.Delete(filedest2);
                        }
                        catch (System.IO.IOException e)
                        {
                            Console.WriteLine(e.Message);
                            Console.ReadLine();
                            return;
                        }
                        try
                        {
                            System.IO.File.Delete(filedest3);
                        }
                        catch (System.IO.IOException e)
                        {
                            Console.WriteLine(e.Message);
                            Console.ReadLine();
                            return;
                        }
                        try
                        {
                            System.IO.File.Delete(filedest4);
                        }
                        catch (System.IO.IOException e)
                        {
                            Console.WriteLine(e.Message);
                            Console.ReadLine();
                            return;
                        }
                    }
                }
            }
        }
 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;
 }
Beispiel #39
0
 public void SetaTabela()
 {
     System.IO.StreamReader file = new System.IO.StreamReader(pathTable);
     for (int i = 0; i < colunas.Length; i++)
     {
         colunas[i].text = "";
     }
     while ((line = file.ReadLine()) != null)
     {
         if (endGame)
         {
             endGame.SetActive(false);
         }
         // Debug.Log("oque?" + line);
         if (line == "NOVA TABELA VERDADE")    //verifica se é um tabela
         {
             line         = file.ReadLine();
             _tableNumber = Convert(line[0]); // pega o numero dessa tabela e convert p int
             if (_tableNumber == counter)     //instruçoes de leitura aqui
             // Debug.Log("Tabela " + tableNumber);
             {
                 line           = file.ReadLine();   //pega expressao
                 expressao.text = line;
                 expr           = SplitString(line); //separa expr pra associar uma coluna da tabela a uma variavel
                 line           = file.ReadLine();   //pega num de linhas da tabela
                 _numLinhas     = Convert(line[0]);  //Debug.Log(numLinhas); Debug.Log(expr);
                 double totalDeLinhas = Math.Pow(2, System.Convert.ToDouble(_numLinhas));
                 _acertos = new int[System.Convert.ToInt32(totalDeLinhas)];
                 Debug.Log(totalDeLinhas);
                 for (int i = 0; i < totalDeLinhas; i++)                                                               //a partir da conta do total de linhas pega tdas as linhas
                 {
                     line      = file.ReadLine();                                                                      //linha da tabela
                     inputs[i] = Instantiate(inputPrefab, new Vector3(0, -75.5f - (85f * i), 0), Quaternion.identity); //seta novo input em sua coordenada
                     inputs[i].transform.SetParent(_resultadoTransform, false);                                        //seta como child de Resultados
                     SetId inputScript = inputs[i].GetComponent <SetId>();                                             //busca script pra setar o id de cada input
                     inputScript.Id           = i;
                     inputs[i].characterLimit = 1;                                                                     //seta limite de caracteres como apenas 1
                     if (_vars > _numLinhas)
                     {
                         expr2 = KnowWhatIterate(expr, i);
                         foreach (var item in expr2)
                         {
                             if (item.Contains("-"))
                             {
                                 colunas[(_convertColunas[item].GetHashCode() - 5)].text += line[_count] + "\n"; //escreve a linha da tabela no postivo
                                 if (line[_count] == 'V')                                                        // nega a linha da tabela e escreve no negativo
                                 {
                                     colunas[_convertColunas[item].GetHashCode()].text += 'F' + "\n";
                                 }
                                 else
                                 {
                                     colunas[_convertColunas[item].GetHashCode()].text += 'V' + "\n";
                                 }
                                 _count += 2;
                             }
                             else
                             {
                                 colunas[_convertColunas[item].GetHashCode()].text += line[_count] + "\n";
                                 _count += 2;
                             }
                         }
                         _count = 0;
                     }
                     else
                     {
                         foreach (var item in expr)   //associa cada coluna da tabela a uma variavel e printa na tela
                         {
                             if (item != null)
                             {
                                 if (item.Contains("-"))
                                 {
                                     colunas[(_convertColunas[item].GetHashCode() - 5)].text += line[_count] + "\n"; //escreve a linha da tabela no postivo
                                     if (line[_count] == 'V')                                                        // nega a linha da tabela e escreve no negativo
                                     {
                                         colunas[_convertColunas[item].GetHashCode()].text += 'F' + "\n";
                                     }
                                     else
                                     {
                                         colunas[_convertColunas[item].GetHashCode()].text += 'V' + "\n";
                                     }
                                     _count += 2;
                                 }
                                 else
                                 {
                                     colunas[_convertColunas[item].GetHashCode()].text += line[_count] + "\n";
                                     _count += 2;
                                 }
                             }
                         }
                         _count = 0;
                     }
                 }
                 file.ReadLine();            //lê o espaço entre a tabela e as respostas
                 resps = file.ReadLine();
                 resp  = SplitString(resps); //separa o vetor de respostas p associar aos inputs
                 counter++;
                 break;
             }
         }
         if ((line = file.ReadLine()) == null)   //vai para algum lugar, fim do arquivo de tabelas**
         {
             TimeScript timer = time.GetComponent <TimeScript>();
             _tempos[userCount] = timer.EndGame();// Debug.Log("atualiza text");
             for (int i = 0; i < _tempos.Length; i++)
             {
                 if (_users[i] != null)   //Debug.Log("USERS " + users[i] + "TEMPOS " + tempos[i]);
                 {
                     userTable.text += String.Format("{0,-12}{1,24}\n", _users[i], _tempos[i] + " segundos");
                 }
             }
             endFile.SetActive(true); //Debug.Log("não tem mais tabela");
             file.DiscardBufferedData();
             //line = file.ReadLine();
             //path = "";
             //pathTable = "/Assets/NewAdds/";
             // file.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
         }
     }
 }
Beispiel #40
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;
        }
Beispiel #41
0
 /// <summary>
 /// Reset to Original position 0
 /// </summary>
 public void Reset()
 {
     file.DiscardBufferedData();
     file.BaseStream.Seek(0, SeekOrigin.Begin);
     file.BaseStream.Position = 0;
 }
Beispiel #42
0
        private bool GetEncoding(LogFile logFile)
        {
            logFile.HasBom   = false;
            logFile.Encoding = Encoding.GetEncoding("ISO-8859-1"); // extended ascii

            try
            {
                // ascii will be default as it never has bom if all fail utf-7 rarely used and does
                // not have preamble. wiki says 2b,2f,76,variable
                SetStatus("GetEncoding:enter: " + logFile.Tag);

                Encoding[] encodings = new Encoding[] { Encoding.UTF32, Encoding.UTF8, Encoding.BigEndianUnicode, Encoding.Unicode };

                //logFile.FileName = Path.GetFileName(fileName);
                // find bom
                bool foundEncoding = false;

                using (System.IO.StreamReader sr = new System.IO.StreamReader(logFile.Tag, true))
                {
                    // encoding = sr.CurrentEncoding;

                    SetStatus("current encoding:" + logFile.Encoding.EncodingName);
                    // biggest preamble is 4 bytes
                    if (sr.BaseStream.Length < 4)
                    {
                        return(true);
                    }

                    int[] srBytes = new int[4];
                    for (int c = 0; c < srBytes.Length; c++)
                    {
                        srBytes[c] = sr.BaseStream.ReadByte();
                    }

                    sr.DiscardBufferedData();

                    foreach (Encoding enc in encodings)
                    {
                        byte[] bytes = enc.GetPreamble();
                        for (int i = 0; i < bytes.Length; i++)
                        {
                            if (bytes[i] != srBytes[i])
                            {
                                foundEncoding = false;
                                break;
                            }
                            else
                            {
                                foundEncoding = true;
                            }
                        }

                        if (foundEncoding)
                        {
                            logFile.HasBom   = true;
                            logFile.Encoding = enc;
                            return(true);
                        }
                    }

                    // if bom not supplied, try to determine utf-16 (unicode)

                    while (!sr.EndOfStream)
                    {
                        string line    = sr.ReadLine();
                        byte[] bytes   = Encoding.UTF8.GetBytes(line);
                        string newLine = Encoding.UTF8.GetString(bytes).Replace("\0", "");
                        SetStatus(string.Format("check encoding: bytes:{0} string: {1}", bytes.Length, newLine.Length));

                        if (bytes.Length > 0 && newLine.Length > 0 &&
                            ((bytes.Length - newLine.Length) * 2 - 1 == bytes.Length
                             | (bytes.Length - newLine.Length) * 2 == bytes.Length))
                        {
                            SetStatus(string.Format("new encoding:Unicode bytes:{0} string: {1}", bytes.Length, newLine.Length));
                            logFile.Encoding = Encoding.Unicode;

                            SetStatus("new encoding:" + logFile.Encoding.EncodingName);
                            break;
                        }
                        else if (bytes.Length > 0 && newLine.Length > 0)
                        {
                            break;
                        }
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                SetStatus("Exception:GetEncoding:" + e.ToString());
                return(false);
            }
        }
Beispiel #43
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);
                    }
                }
            }
        }
Beispiel #44
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;
        }
Beispiel #45
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;
 }
Beispiel #46
0
        private bool readBCI2000dat(string filename, out Data_BCI2000 info, out double[][] samples)
        {
            FileStream   dataStream = null;
            StreamReader dataReader = null;

            // check if the file exists
            if (!File.Exists(filename))
            {
                MessageBox.Show("Could not find input file", "File error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                info    = null;
                samples = null;
                return(false);
            }

            try {
                // open file stream
                dataStream = new FileStream(filename, FileMode.Open);

                // open reader
                //dataReader = new System.IO.StreamReader(filestream, System.Text.Encoding.UTF8, true, 128);
                dataReader = new System.IO.StreamReader(dataStream);
            } catch (Exception) {
                // message
                MessageBox.Show("Could not create filestream to data file '" + filename + "' for reading");
                info    = null;
                samples = null;
                return(false);
            }

            // create a new bci2000 data object
            info = new Data_BCI2000();

            // retrieve the first line
            info.firstLine = dataReader.ReadLine();

            // retrieve HeaderLen
            string fieldName        = "HeaderLen=";
            int    fieldValueLength = 6;
            int    pos = info.firstLine.IndexOf(fieldName);

            if (pos == -1 || info.firstLine.Length < pos + fieldName.Length + fieldValueLength)
            {
                MessageBox.Show("Could not retrieve " + fieldName + ", aborting");
                info    = null;
                samples = null;
                return(false);
            }
            bool result = Int32.TryParse(info.firstLine.Substring(pos + fieldName.Length, fieldValueLength), out info.headerLen);

            if (!result)
            {
                MessageBox.Show("Could not retrieve " + fieldName + ", aborting");
                info    = null;
                samples = null;
                return(false);
            }

            // retrieve SourceCh
            fieldName        = "SourceCh=";
            fieldValueLength = 2;
            pos = info.firstLine.IndexOf(fieldName);
            if (pos == -1 || info.firstLine.Length < pos + fieldName.Length + fieldValueLength)
            {
                MessageBox.Show("Could not retrieve " + fieldName + ", aborting");
                info    = null;
                samples = null;
                return(false);
            }
            result = Int32.TryParse(info.firstLine.Substring(pos + fieldName.Length, fieldValueLength), out info.sourceCh);
            if (!result)
            {
                MessageBox.Show("Could not retrieve " + fieldName + ", aborting");
                info    = null;
                samples = null;
                return(false);
            }

            // retrieve StatevectorLen
            fieldName = "StatevectorLen=";
            //fieldValueLength = 3;
            pos = info.firstLine.IndexOf(fieldName);
            fieldValueLength = Math.Min(3, info.firstLine.Length - (pos + fieldName.Length));               // adjusted: fieldValueLength is variable: so it is either three, or in case the string is shorter, the remainder of the string: either 1 or 2
            if (pos == -1 || info.firstLine.Length < pos + fieldName.Length + fieldValueLength)
            {
                MessageBox.Show("Could not retrieve " + fieldName + ", aborting");
                info    = null;
                samples = null;
                return(false);
            }
            result = Int32.TryParse(info.firstLine.Substring(pos + fieldName.Length, fieldValueLength), out info.stateVectorLen);
            if (!result)
            {
                MessageBox.Show("Could not retrieve " + fieldName + ", aborting");
                info    = null;
                samples = null;
                return(false);
            }

            // retrieve entire header
            char[] buffer = new char[info.headerLen];
            dataStream.Position = 0;
            dataReader.DiscardBufferedData();
            dataReader.ReadBlock(buffer, 0, info.headerLen);
            info.header = new string(buffer);

            // retrieve the sample rate from the header
            if (!getDoubleParameterFromHeader(info.header, "SamplingRate", out info.samplingRate))
            {
                MessageBox.Show("Could not retrieve sample rate from header, aborting");
                info    = null;
                samples = null;
                return(false);
            }

            // set the dataStream position to the start of the data (needed, readblock before messed it up)
            dataStream.Position = info.headerLen;

            // set
            int mDataSize = 2;      // each sample in BCI2000 is stored as an int16 (2 bytes)

            // calculate the number of samples
            info.numSamples = (int)(dataStream.Length - info.headerLen) / (mDataSize * info.sourceCh + info.stateVectorLen);

            // init matrix for all samples values
            samples = new double[info.numSamples][];

            // retrieve the data
            for (int i = 0; i < info.numSamples; i++)
            {
                // init the row of samples
                samples[i] = new double[info.sourceCh];

                // read the samples
                byte[] channels = new byte[mDataSize * info.sourceCh];
                dataStream.Read(channels, 0, mDataSize * info.sourceCh);

                // convert each channel
                for (int j = 0; j < info.sourceCh; j++)
                {
                    samples[i][j] = BitConverter.ToInt16(channels, j * mDataSize);
                }

                // read the state vector data
                byte[] stateVector = new byte[info.stateVectorLen];
                dataStream.Read(stateVector, 0, info.stateVectorLen);

                // TODO: interpret state vector
            }

            // close the datastream
            if (dataStream != null)
            {
                dataStream.Close();
            }
            dataReader = null;
            dataStream = null;

            // return success
            return(true);
        }
Beispiel #47
0
        private void LoadHike_Click(object sender, EventArgs e)
        {
            if (openHikeDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(openHikeDialog.FileName);
                    //(System.IO.FileStream)saveHikeDialog.OpenFile());

                    //clear the current hike
                    ClearMap();
                    int count = 0;
                    while (sr.ReadLine() != null)
                    {
                        count++;
                    }
                    hike = new LocPoint[count];
                    MainMap.Refresh();

                    //load points into hike variable
                    string   line;
                    string[] lineParts = new string[11];
                    sr.DiscardBufferedData();
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    count = 0;
                    while ((line = sr.ReadLine()) != null)
                    {
                        lineParts = line.Split(',');
                        hike[count].degreeNorthSouth = Convert.ToInt32(lineParts[0]);
                        hike[count].minuteNorthSouth = Convert.ToSingle(lineParts[1]);
                        hike[count].northSouth       = Convert.ToChar(lineParts[2]);
                        hike[count].degreeEastWest   = Convert.ToInt32(lineParts[3]);
                        hike[count].minuteEastWest   = Convert.ToSingle(lineParts[4]);
                        hike[count].eastWest         = Convert.ToChar(lineParts[5]);
                        hike[count].elevation        = Convert.ToInt32(lineParts[6]);
                        hike[count].capTime.hours    = Convert.ToInt32(lineParts[7]);
                        hike[count].capTime.minutes  = Convert.ToInt32(lineParts[8]);
                        hike[count].capTime.seconds  = Convert.ToInt32(lineParts[9]);
                        hike[count].distancedHiked   = Convert.ToDouble(lineParts[10]);

                        count++;
                    }

                    //put points on the map
                    AddPointsToMap();
                    MainMap.Refresh();

                    //allow the user to save hikes
                    SaveHike.Enabled = true;
                }
                catch
                {
                    //error opening file
                    MessageBox.Show("Error opening file", "Error");
                }
            }
            else
            {
                //not a valid file
            }
        }
Beispiel #48
0
        /// <summary>
        /// was a static function, returns max index, min values, max values arrays as a reference
        /// </summary>
        public void getConfigFileMinMaxValues(string restore_filename, ref double[] feature_max, ref double[] feature_min, ref int max_index)
        {
            max_index = -1;
            StreamReader fp_restore;

            fp_restore = null;
            if (restore_filename != null)
            {
                int    idx, c;
                double fmin, fmax;
                string restore_line;
                double lower = -1.0;
                double upper = 1.0;
                double y_lower;
                double y_upper;
                bool   y_scaling = false;
                double y_max     = -System.Double.MaxValue;
                double y_min     = System.Double.MaxValue;

                //open file.
                try
                {
                    fp_restore = new StreamReader(restore_filename);
                }
                catch (System.Exception e)
                {
                    System.Console.Error.WriteLine("can't open file " + restore_filename);
                }

                //STEP - 1: find max index
                if (fp_restore.Read() == 'y')
                {
                    fp_restore.ReadLine();
                    fp_restore.ReadLine();
                    fp_restore.ReadLine();
                }
                fp_restore.ReadLine();
                fp_restore.ReadLine();

                restore_line = null;
                while ((restore_line = fp_restore.ReadLine()) != null)
                {
                    idx       = int.Parse(restore_line.Split(',')[0]);
                    max_index = System.Math.Max(max_index, idx);
                }

                //STEP2: allocate memory
                try
                {
                    feature_max = new double[(max_index + 1)];
                    feature_min = new double[(max_index + 1)];
                }
                catch (OutOfMemoryException e)
                {
                    System.Console.Error.WriteLine("can't allocate enough memory");
                }

                //rewind stream.
                fp_restore.BaseStream.Position = 0;
                fp_restore.DiscardBufferedData();

                //STEP - 3: find all min/max values
                if (fp_restore.Read() == 'y')
                {
                    fp_restore.ReadLine();                              // pass the '\n' after 'y'
                    restore_line = fp_restore.ReadLine();
                    string[] restore_line_ar = restore_line.Split(',');
                    y_lower = double.Parse(restore_line_ar[0]);
                    y_upper = double.Parse(restore_line_ar[1]);

                    restore_line    = fp_restore.ReadLine();
                    restore_line_ar = restore_line.Split(',');
                    y_min           = double.Parse(restore_line_ar[0]);
                    y_max           = double.Parse(restore_line_ar[1]);
                    y_scaling       = true;
                }
                else
                {
                    fp_restore.BaseStream.Position = 0;
                    fp_restore.DiscardBufferedData();
                }

                if (fp_restore.Read() == 'x')
                {
                    fp_restore.ReadLine();              // pass the '\n' after 'x'
                    restore_line = fp_restore.ReadLine();
                    string[] restore_line_ar = restore_line.Split(',');
                    lower = double.Parse(restore_line_ar[0]);
                    upper = double.Parse(restore_line_ar[1]);

                    restore_line    = null;
                    restore_line_ar = null;
                    while ((restore_line = fp_restore.ReadLine()) != null)
                    {
                        restore_line_ar = restore_line.Split(',');
                        idx             = int.Parse(restore_line_ar[0]);
                        fmin            = double.Parse(restore_line_ar[1]);
                        fmax            = double.Parse(restore_line_ar[2]);
                        if (idx <= max_index) // this will ignore index 204801 if the max is 204800
                        {
                            feature_min[idx] = fmin;
                            feature_max[idx] = fmax;
                        }
                    }
                }
                fp_restore.Close();
            }
        }
Beispiel #49
0
        private void btnLoadMultiBoundaryFromGE_Click(object sender, EventArgs e)
        {
            string fileAndDirectory;
            {
                //create the dialog instance
                OpenFileDialog ofd = new OpenFileDialog
                {
                    //set the filter to text KML only
                    Filter = "KML files (*.KML)|*.KML",

                    //the initial directory, fields, for the open dialog
                    InitialDirectory = mf.fieldsDirectory + mf.currentFieldDirectory
                };

                //was a file selected
                if (ofd.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }
                else
                {
                    fileAndDirectory = ofd.FileName;
                }
            }

            //start to read the file
            string line = null;
            int    index;

            using (System.IO.StreamReader reader = new System.IO.StreamReader(fileAndDirectory))
            {
                int bndCount = 0;

                ResetAllBoundary();

                while (!reader.EndOfStream)
                {
                    line  = reader.ReadLine();
                    index = line.IndexOf("<coordinates>");

                    if (index != -1)
                    {
                        bndCount++;
                    }
                }

                reader.DiscardBufferedData();
                reader.BaseStream.Seek(0, SeekOrigin.Begin);
                reader.BaseStream.Position = 0;

                if (bndCount > 0)
                {
                }

                try
                {
                    for (int i = 0; i < bndCount; i++)
                    {
                        //step thru the file till first boundary
                        while (!reader.EndOfStream)
                        {
                            line  = reader.ReadLine();
                            index = line.IndexOf("<coord");
                            if (index != -1)
                            {
                                break;
                            }
                        }

                        line = reader.ReadLine();
                        line = line.Trim();
                        char[]   delimiterChars = { ' ', '\t', '\r', '\n' };
                        string[] numberSets     = line.Split(delimiterChars);

                        //at least 3 points
                        if (numberSets.Length > 2)
                        {
                            //reset boundary
                            foreach (var item in numberSets)
                            {
                                string[] fix = item.Split(',');
                                double.TryParse(fix[0], NumberStyles.Float, CultureInfo.InvariantCulture, out lonK);
                                double.TryParse(fix[1], NumberStyles.Float, CultureInfo.InvariantCulture, out latK);
                                double[] xy = mf.pn.DecDeg2UTM(latK, lonK);

                                //match new fix to current position
                                easting  = xy[0] - mf.pn.utmEast;
                                northing = xy[1] - mf.pn.utmNorth;

                                //fix the azimuth error
                                easting  = (Math.Cos(-mf.pn.convergenceAngle) * easting) - (Math.Sin(-mf.pn.convergenceAngle) * northing);
                                northing = (Math.Sin(-mf.pn.convergenceAngle) * easting) + (Math.Cos(-mf.pn.convergenceAngle) * northing);

                                //add the point to boundary
                                CBndPt bndPt = new CBndPt(easting, northing, 0);
                                mf.bnd.bndArr[i].bndLine.Add(bndPt);
                            }

                            //fix the points if there are gaps bigger then
                            mf.bnd.bndArr[i].CalculateBoundaryHeadings();
                            mf.bnd.bndArr[i].PreCalcBoundaryLines();
                            mf.bnd.bndArr[i].FixBoundaryLine(i);

                            //boundary area, pre calcs etc
                            mf.bnd.bndArr[i].CalculateBoundaryArea();
                            mf.bnd.bndArr[i].PreCalcBoundaryLines();
                            mf.bnd.bndArr[i].isSet         = true;
                            mf.bnd.bndArr[i].isDriveAround = true;
                        }
                        else
                        {
                            mf.TimedMessageBox(2000, "Error reading KML", "Choose or Build a Different one");
                        }
                    }

                    mf.FileSaveBoundary();
                    UpdateChart();
                    cboxSelectBoundary.Enabled = true;
                }
                catch (Exception)
                {
                    return;
                }
            }
        }
        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);
                    }
                }
            }
        }
Beispiel #51
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;
        }
Beispiel #52
0
    // ----------------------------------------------------
    // CityStates.txt

    static void CityStates()
    {
        string line3;

        System.IO.StreamReader file3 = new System.IO.StreamReader("cities.txt");

        // List to hold cities in cities.txt
        List <string> cities = new List <string>();

        // add cities to cities list
        while ((line3 = file3.ReadLine()) != null)
        {
            cities.Add(line3);
        }

        System.IO.StreamReader zipcodes3  = new System.IO.StreamReader("zipcodes.txt");
        List <string>          CityStates = new List <string>();

        // for each city, check each line of zipcodes for matching city
        // if city matches, add it to CityStates
        foreach (string city in cities)
        {
            // move to beginning of zipcodes.txt for each city
            zipcodes3.DiscardBufferedData();
            zipcodes3.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

            CityStates.Add("\n");
            CityStates.Add(city);
            while ((line3 = zipcodes3.ReadLine()) != null)
            {
                string[] words3 = line3.Split('\t');
                // add states to CityStates list if they have the given city
                if (words3[3] == city.ToUpper())
                {
                    CityStates.Add(words3[4]);
                }
            }
        }

        List <string> CityStates2 = new List <string>();

        using (StreamWriter writeText3 = new StreamWriter("CityStates.txt")) {
            foreach (string entry in CityStates)
            {
                // if entry is the name of the city
                if (entry.Length != 2)
                {
                    CityStates2.Sort();
                    foreach (string cityState in CityStates2)
                    {
                        writeText3.Write(cityState + " ");
                    }
                    // clear the list for the next city
                    CityStates2.Clear();
                    writeText3.Write(entry);
                    writeText3.Write(" ");
                }
                else if (entry.Length == 2 && !CityStates2.Contains(entry))
                {
                    CityStates2.Add(entry);
                }
            }
            // at end of CityStates, sort and write CityStates2
            CityStates2.Sort();
            foreach (string cityState in CityStates2)
            {
                writeText3.Write(cityState + " ");
            }
        }
        file3.Close();
        zipcodes3.Close();
    }