static void Main(string[] args)
    {
        if (args.Length < 2) {
            Console.WriteLine("Usage: BenchSgmlReader.exe filename iterations");
            return;
        }

        var streamReader = new StreamReader(args[0]);
        string text = streamReader.ReadToEnd();
        streamReader.Close();

        int n = int.Parse(args[1]);

        var start = DateTime.Now;
        for (int i = 0; i < n; i++) {
            SgmlReader sgmlReader = new SgmlReader();
            sgmlReader.DocType = "HTML";
            sgmlReader.WhitespaceHandling = WhitespaceHandling.All;
            //sgmlReader.CaseFolding = Sgml.CaseFolding.ToLower;
            sgmlReader.InputStream = new StringReader(text);

            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.XmlResolver = null;
            doc.Load(sgmlReader);
        }
        var stop = DateTime.Now;

        var duration = stop - start;
        Console.WriteLine("{0} s", (duration.TotalMilliseconds / 1000.0).ToString(CultureInfo.InvariantCulture));
    }
Exemple #2
0
        static void Main(string[] args)
        {
            Settings.LoadOrInitialize();
            InitializePreset();

            var watcher = new FileSystemWatcher
            {
                Path         = Settings.ChatLogFolder,
                NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess,
                Filter       = _currentPreset.Channel + "_*.txt"
            };

            try
            {
                watcher.Changed            += OnChanged;
                watcher.Created            += OnCreated;
                watcher.EnableRaisingEvents = true;
                WaitForUserInput();
            }
            finally
            {
                _intelStreamReader?.Close();
                _intelFileStream?.Close();
            }
        }
Exemple #3
0
    protected void btnInstall_Click(object sender, EventArgs e)
    {
        string ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\{0}.mdb;",
                txtDatabaseName.Text);
        OleDbConnection OConn = new OleDbConnection(ConnectionString);
        StreamReader Sr = new StreamReader(Server.MapPath("~/Setup/Scripts/Access.sql"));
        try
        {
            File.Copy(Server.MapPath("~/Setup/Scripts/Blogsa.mdb"), Server.MapPath(string.Format("~/App_Data/{0}.mdb", txtDatabaseName.Text)));

            //Update WebSite Url
            string strUrl = Request.Url.AbsoluteUri.Substring(0
                , Request.Url.AbsoluteUri.IndexOf(Request.Url.AbsolutePath) + (Request.ApplicationPath.Equals("/") ? 0 : Request.ApplicationPath.Length)) + "/";

            OConn.Open();
            while (!Sr.EndOfStream)
            {
                //Create DB
                string Commands = Sr.ReadLine().ToString();
                if (!Commands.StartsWith("/*"))
                {
                    OleDbCommand OComm = new OleDbCommand(Commands, OConn);
                    OComm.ExecuteNonQuery();
                    OComm.Dispose();
                }
            }

            Sr.Close();
            string strLang = (string)Session["lang"];
            string strRedirectPage = String.Format("Completed.aspx?Setup={0}&lang={1}", BSHelper.SaveWebConfig(ConnectionString, "System.Data.OleDb"), strLang);
            Response.Redirect(strRedirectPage, false);
        }
        catch (Exception ex)
        {
            BSLog l = new BSLog();
            l.CreateDate = DateTime.Now;
            l.LogType = BSLogType.Error;
            l.LogID = Guid.NewGuid();
            l.RawUrl = Request.RawUrl;
            l.Source = ex.Source;
            l.StackTrace = ex.StackTrace;
            l.TargetSite = ex.TargetSite;
            l.Url = Request.Url.ToString();
            l.Save();

            divError.Visible = true;
            lblError.Text = ex.Message;
            if (OConn.State == ConnectionState.Open)
            {
                OConn.Close();
            }
            File.Delete(Server.MapPath("~/App_Data/" + txtDatabaseName.Text));
        }
        finally
        {
            if (OConn.State == ConnectionState.Open)
                OConn.Close();
            Sr.Close();
        }
    }
    public static void Main(String[] args)
    {
        StreamReader sr=null;
        StreamWriter sw=null;
        TcpClient client=null;
        TcpListener server=null;
        try {
          //Echo servers listen on port 7
          int portNumber = 7;

          //Echo server first binds to port 7
          server = new TcpListener(portNumber);
          //Server starts listening
          server.Start();

          //Echo server loops forever, listening for clients
          for(;;) {
        Console.WriteLine("Waiting for a connection....");

        //Accept the pending client connection and return a client
        //initialized for communication
        //This method will block until a connection is made
        client = server.AcceptTcpClient();
        Console.WriteLine("Connection accepted.");

        //Make a user-friendly StreamReader from the stream
        sr=new StreamReader(client.GetStream());

        //Make a user-friendly StreamWriter from the stream
        sw=new StreamWriter(client.GetStream());

        String incoming=sr.ReadLine();
        while (incoming!=".") {
        Console.WriteLine("Message received: "+incoming);
        sw.WriteLine(incoming);
        sw.Flush();
        Console.WriteLine("Message Sent back: " + incoming);
        incoming=sr.ReadLine();
        }
        Console.WriteLine("Client sent '.': closing connection.");
        sr.Close();
        sw.Close();
        client.Close();
          }
        } catch (Exception e) {
        Console.WriteLine(e+" "+e.StackTrace);
        } finally {
        if (sr!=null) sr.Close();//check if the stream reader is present - if it is, close it
        if (sw!=null) sw.Close();//check if the stream writer is present - if it is, close it
        if (client!=null) client.Close();
        //Release the port and stop the server
        server.Stop();
        }
    }
Exemple #5
0
    public static void Main()
    {
        try
        {
            bool status = true ;
            string servermessage = "" ;
            string clientmessage = "" ;
            TcpListener tcpListener = new TcpListener(8100) ;
            tcpListener.Start() ;
            Console.WriteLine("Server Started") ;

            Socket socketForClient = tcpListener.AcceptSocket() ;
            Console.WriteLine("Client Connected") ;
            NetworkStream networkStream = new NetworkStream(socketForClient) ;
            StreamWriter streamwriter = new StreamWriter(networkStream) ;
            StreamReader streamreader = new StreamReader(networkStream) ;

            while(status)
            {
                if(socketForClient.Connected)
                {
                    servermessage = streamreader.ReadLine() ;
                    Console.WriteLine("Client:"+servermessage) ;
                    if((servermessage== "bye" ))
                    {
                        status = false ;
                        streamreader.Close() ;
                        networkStream.Close() ;
                        streamwriter.Close() ;
                        return ;

                    }
                    Console.Write("Server:") ;
                    clientmessage = Console.ReadLine() ;

                    streamwriter.WriteLine(clientmessage) ;
                    streamwriter.Flush() ;
                }

            }
            streamreader.Close() ;
            networkStream.Close() ;
            streamwriter.Close() ;
            socketForClient.Close() ;
            Console.WriteLine("Exiting") ;
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString()) ;
        }
    }
	// Update is called once per frame
	void Update () {

		// read the cube color from the text file
		// we use fileReadTimer to slow down the read frequency
		if (fileReadTimer++ > 10) {
	        // create reader & open file
	        TextReader tr = new StreamReader("data.txt");
	        // read a line of text
	        ReceivedColor = tr.ReadLine();
	        // close the stream
	        tr.Close();
			
			fileReadTimer = 0;  // reset the timer
		}
	
		// set the Cub color
		switch (ReceivedColor) {
			case "white":
				GetComponent<Renderer>().material.color = Color.white;
				break;
			case "red":
				GetComponent<Renderer>().material.color = Color.red;
				break;
			case "blue":
				GetComponent<Renderer>().material.color = Color.blue;
				break;
			case "green":
				GetComponent<Renderer>().material.color = Color.green;
				break;
			case "yellow":
				GetComponent<Renderer>().material.color = Color.yellow;
				break;
			
		}
	}
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\input.txt");

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

        string currLine = null;

        while (1 == 1)
        {
            currLine = reader.ReadLine();//Line1 (1/3/5/7)
            currLine = reader.ReadLine();//Line2 (4/6/8/10)
            if (currLine == null)
            {
                break;
            }
            allEvenLines.Add(currLine);
        }
        reader.Close();

        StreamWriter writer = new StreamWriter(@"..\..\input.txt", false); // after closing the reader
        foreach (string line in allEvenLines)
        {
            writer.WriteLine(line);
        }
        writer.Close();
    }
	public  void cargar(){



		int numero = 0;
		StreamReader sr = new StreamReader (ruta);

		while (sr.ReadLine()!=null) {

			numero++;

		}
		sr.Close ();
		sr = new StreamReader (ruta);

		 arreglo = new string[numero];
		Debug.Log (arreglo.Length);


		for (int i=0; i<arreglo.Length; i++) {

			String linea=sr.ReadLine();
			arreglo[i]=linea;
		}
		sr.Close ();



	}
    static void Main()
    {
        var reader = new StreamReader("..\\..\\input.txt");
        string[] input = reader.ReadToEnd().Split(' ');
        reader.Close();
        string deletedWord = "start";
        string newWord = "finish";
        for (int i = 0; i < input.Length; i++)
        {
            if (input[i]==deletedWord)
            {
                input[i] = newWord;
            }
        }
        string result = string.Join(" ", input);
        var writer = new StreamWriter("..\\..\\result.txt");
        using (writer)
        {
            if (result != null)
            {
                writer.WriteLine(result);
            }

        }
    }
 public static void read(out SaveProfile instance)
 {
     string currentDirectory = Directory.GetCurrentDirectory();
     string path = currentDirectory + "\\setting.xml";
     if (File.Exists(path))
     {
         XmlSerializer xmlSerializer = new XmlSerializer(typeof(SaveProfile));
         TextReader textReader = new StreamReader(path);
         instance = (SaveProfile)xmlSerializer.Deserialize(textReader);
         textReader.Close();
     }
     else
     {
         instance = new SaveProfile
         {
             look = 5f,
             blink = 5f,
             wink_l = 5f,
             wink_r = 5f,
             brow = 5f,
             teeth = 5f,
             smile = 5f,
             smirk_l = 5f,
             smirk_r = 5f
         };
     }
 }
    public static void UpdateUnityAppController(string path)
    {
        const string filePath = "Classes/UnityAppController.mm";
        string fullPath = Path.Combine(path, filePath);

        var reader = new StreamReader(fullPath);
        string AppControllerSource = reader.ReadToEnd();
        reader.Close();

        // Add header import
        AppControllerSource = AddHeaderImportFramework(AppControllerSource);

        // Add Appota Handler Callback
        AppControllerSource = AddAppotaHandlerCallback(AppControllerSource);

        // Add callback register Push Notification
        AppControllerSource = AddCallbackRegisterPushNotifications(AppControllerSource);

        // Call Facebook activeApp() inside applicationDidBecomeActive function
        AppControllerSource = AddFacebookAppEvents(AppControllerSource);

        // Add callback register Push Notification with Token data
        AppControllerSource = AddCallbackRegisterPushNotificationWithTokenData(AppControllerSource);

        if (AppotaSetting.UsingAppFlyer)
            AppControllerSource = AddAppFlyerConfigure(AppControllerSource);

        if (AppotaSetting.UsingAdWords)
            AppControllerSource = AddAdWordsConfigure(AppControllerSource);

        var writer = new StreamWriter(fullPath, false);
        writer.Write(AppControllerSource);
        writer.Close();
    }
 static void Main()
 {
     try
     {
         StreamReader readFile = new StreamReader("..\\..\\text.txt");
         try
         {
             string line = readFile.ReadLine();
             for (int index = 1; line != null ; index ++)
             {
                 if (index % 2 != 0)
                 {
                     Console.WriteLine(line);
                 }
                 line = readFile.ReadLine();
             }
         }
         finally
         {
             readFile.Close();
         }
     }
     catch (Exception exp)
     {
         Console.WriteLine(exp.Message);
     }
 }
    public void Adjust(string fileName)
    {
        try
        {
            string path = Path.GetDirectoryName(Application.dataPath+"..");
            if (File.Exists(path+"/"+fileName))
            {
                TextReader tx = new StreamReader(path+"/"+fileName);
                if (doc == null)
                    doc = new XmlDocument();
                doc.Load(tx);
                tx.Close();
                if (doc!=null && doc.DocumentElement!=null)
                {
                    string xmlns = doc.DocumentElement.Attributes["xmlns"].Value;
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("N",xmlns);

                    SetNode("TargetFrameworkVersion","v4.0", nsmgr);
                    // SetNode("DefineConstants","TRACE;UNITY_3_5_6;UNITY_3_5;UNITY_EDITOR;ENABLE_PROFILER;UNITY_STANDALONE_WIN;ENABLE_GENERICS;ENABLE_DUCK_TYPING;ENABLE_TERRAIN;ENABLE_MOVIES;ENABLE_WEBCAM;ENABLE_MICROPHONE;ENABLE_NETWORK;ENABLE_CLOTH;ENABLE_WWW;ENABLE_SUBSTANCE", nsmgr);

                    TextWriter txs = new StreamWriter(path+"/"+fileName);
                    doc.Save(txs);
                    txs.Close();
                }
            }
        }
        catch(System.Exception)
        {
        }
    }
Exemple #14
0
    void Start()
    {
        Punteggio.score = 0;
        StreamReader streamReader = new StreamReader("settings.txt");
        //scorro le prime linee che non mi servono
        for (int i = 0; i<3; i++) {
            streamReader.ReadLine();
        }

        //prendo la difficolta in char -48 per avere l intero corispondente
        NumeroCubiDaSpawnarestr = streamReader.ReadLine();
        print (NumeroCubiDaSpawnarestr);
        NumeroCubiDaSpawnare = int.Parse(NumeroCubiDaSpawnarestr);

        streamReader.Close();

        if (Start_Scene) {
            Color[] Colori = {Color.red, Color.blue, Color.magenta, Color.green, Color.yellow};
            //creo i cubi in posizione random  e ne assegno un colore
            for (int i = 0; i<NumeroCubiDaSpawnare; i++) {
                Vector3 RandomPos = new Vector3 (Random.Range (1.014049f, 1.43f), 1.112f, Random.Range (1.479741f, 2.097f));
                Color CubeColor = colors [Random.Range (0, colors.Length)];//colors[Random.Range (0, 5)];
                GameObject clone = Instantiate (cubo, RandomPos, Quaternion.identity) as GameObject;
                clone.renderer.material.color = CubeColor;
            }
        }
    }
Exemple #15
0
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
     this.backgroundWorker1.ReportProgress(0, string.Format("{0}に接続中・・・", this.uri));
     this.client = new WebClient();
     while (this.client.IsBusy)
     {
         Thread.Sleep(100);
         if (this.backgroundWorker1.CancellationPending)
         {
             return;
         }
     }
     Stream stream = this.client.OpenRead(this.uri);
     this.backgroundWorker1.ReportProgress(0, string.Format("{0}に接続完了", this.uri));
     this.backgroundWorker1.ReportProgress(0, string.Format("データを読み込み中", this.uri));
     StreamReader reader = new StreamReader(stream);
     string str = reader.ReadToEnd();
     this.xmltext = str;
     reader.Close();
     this.backgroundWorker1.ReportProgress(0, string.Format("完了", this.uri));
     }
     catch (Exception exception)
     {
     throw new Exception(exception.Message);
     }
 }
 private static void loadAllExtensionFiles()
 {
     if (extensionFiles == null)
     {
         string[] filePaths;
         extensionFiles = new Dictionary<String, String>();
         try
         {
             filePaths = Directory.GetFiles("Resources/Extensions/", "*.cs");
         }
         catch (DirectoryNotFoundException)
         {
             return;
         } 
         foreach (String fileName in filePaths)
         {
             TextReader tr = new StreamReader(fileName);
             String result = "";
             while (tr.Peek() >= 0)
             {
                 result += tr.ReadLine() + "\n";
             }
             extensionFiles.Add(fileName, result);
             tr.Close();
         }
     }
 }
Exemple #17
0
 public static JSONNode ReadJson(string path)
 {
     var reader = new StreamReader(path);
     var s = reader.ReadToEnd();
     reader.Close();
     return JSONNode.Parse(s);
 }
	static public void Main ()
	{
		// Create an AlchemyAPI object.
		AlchemyAPI.AlchemyAPI alchemyObj = new AlchemyAPI.AlchemyAPI();


		// Load an API key from disk.
		alchemyObj.LoadAPIKey("api_key.txt");


		// Categorize a web URL by topic.
		string xml = alchemyObj.URLGetCategory("http://www.techcrunch.com/");
		Console.WriteLine (xml);


		// Categorize some text.
		xml = alchemyObj.TextGetCategory("Latest on the War in Iraq.");
		Console.WriteLine (xml);


		// Load a HTML document to analyze.
		StreamReader streamReader = new StreamReader("data/example.html");
		string htmlDoc = streamReader.ReadToEnd();
		streamReader.Close();


		// Categorize a HTML document by topic.
		xml = alchemyObj.HTMLGetCategory(htmlDoc, "http://www.test.com/");
		Console.WriteLine (xml);
	}
 public static String Load(string path){
   if(!Exists(path)) return "";
   StreamReader r = new StreamReader(CompletePath(path));
   string raw = r.ReadToEnd();
   r.Close();
   return raw;
 }
Exemple #20
0
    public void GetMapTool()
    {
        map = new Dictionary<int,Dictionary<int,int>>();
        StreamReader sr = new StreamReader(Application.streamingAssetsPath+"/map.txt", Encoding.Default);
        string line;
        int j = -42;
        while ((line = sr.ReadLine()) != null)
        {
            string[] sArray = line.Split(' ');
            Dictionary<int, int> temp = new Dictionary<int, int>();
            for(int i=-48; i<sArray.Length-48;i++)
            {
                temp.Add(i, System.Int32.Parse(sArray[i + 48]));
                
                //Debug.Log(temp[i]);
            }
            
            map.Add(j, temp);
            j++;
        }
        //string log = "";
        //foreach (var pair in map)
        //{
        //    foreach (var p in pair.Value)
        //    {
        //        log = log + "" + pair.Key + " " + p.Key + " " + p.Value + "\n";
        //    }

        //}
        //this.WriteDebugFile(log,"map.log");
        sr.Close();
        
    }
    // Use this for initialization
    void Start()
    {
        Zoom.OnChangeZoom += OnChangeZoom;
        mg = GameObject.Find ("Manager").GetComponent<Manager> ();
        locationList = new ArrayList ();

        locationListScreen = new ArrayList ();

        using (StreamReader reader = new StreamReader(Application.dataPath + "\\"+RouteListPath)) {
            while (!reader.EndOfStream) {
                string line = reader.ReadLine ();

                string[] parts = line.Split (",".ToCharArray ());
                locationList.Add(new double[]{double.Parse(parts[0]),double.Parse(parts[1])});
            }
            reader.Close();
        }

        lineParameter = "&path=color:0xff0030";

        for (int i=0; i< locationList.Count; i++) {
            double[] d_pos = (double[])locationList [i];
            lineParameter += "|" + d_pos [0].ToString () + "," + d_pos [1].ToString ();
            double[] point = {(double)d_pos [1],  (double)d_pos [0]};
            Vector3 pos = mg.GIStoPos (point);
            locationListScreen.Add (pos);
        }
         #if !(UNITY_IPHONE)
        mg.sy_Map.addParameter = lineParameter;
         #endif
    }
    public List<string> ReadTwineData(string path)
    {
        string temp;
        string[] file;

        try
        {
            //create a stream reader
            //get the data in the text file
            //close the stream reader
            StreamReader sr = new StreamReader(path);
            temp = sr.ReadToEnd();
            sr.Close();

            //parse large string by lines into an list
            file = temp.Split("\n"[0]);
            foreach (string s in file)
            {
                twineInfo.Add(s);
            }
            return twineInfo;
        }

        catch (FileNotFoundException e)
        {
            Debug.Log("The process failed: {0}" + e.ToString());
            return null;
        }
    }
Exemple #23
0
 static void Main()
 {
     StreamReader reader1 = new StreamReader("../../file1.txt");
     StreamReader reader2 = new StreamReader("../../file2.txt");
     string line1 = reader1.ReadLine();
     string line2 = reader2.ReadLine();
     int sameCount = 0;
     int totalCount = 0;
     while (line1 != null) // * Assume the files have equal number of lines.
     {
         if (line1 == line2)
         {
             sameCount++;
         }
         Console.WriteLine("{0} ?= {1} -> {2}", line1, line2, line1 == line2);
         line1 = reader1.ReadLine();
         line2 = reader2.ReadLine();
         totalCount++;
     }
     reader1.Close();
     reader2.Close();
     Console.WriteLine(new string('=', 25));
     Console.WriteLine("Identic lines: {0}", sameCount);
     Console.WriteLine("Different lines: {0}", totalCount - sameCount);
 }
    protected void btnImport_Click(object sender, EventArgs e)
    {
        string path = @"C:\Inetpub\wwwroot\File\" + txtFileName.Text;
        StreamReader sr = new StreamReader(path);

        string strTextToSplit = sr.ReadToEnd();
        strTextToSplit = strTextToSplit.Replace("\r", "");
        string[] arr = strTextToSplit.Split(new char[] { '\n' });

        for (int i = 0; i < arr.GetUpperBound(0); i++)
        {
            arr[i] = arr[i].Replace("Type=\"Number\"", "Type=\"String\"");
            if (arr[i].Substring(0, 13) == "<Row><Cell ss") arr[i] = "";
            if (arr[i].Length > 50 && arr[i].Substring(0, 52) == "<Row><Cell><Data ss:Type=\"String\">Lines with Errors:") arr[i] = "";
            if (arr[i].IndexOf("This Student has already") != -1) arr[i] = "";
        }

        path = @"C:\Inetpub\wwwroot\File\" + txtFileName.Text + ".xml";
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        using (StreamWriter sw = new StreamWriter(path))
        {
            foreach (string s in arr)
            {
                sw.WriteLine(s);
            }
            sw.Close();
        }
        sr.Close();

        Response.Write("DONE");
    }
    public string LoadContain()
    {
        if (Request.QueryString["CourseId"] == null)
        {
            return string.Empty;
        }

        string ThePath = string.Empty;
        string RetData = string.Empty;
        using (OleDbConnection Con = new OleDbConnection(constr))
        {
            OleDbCommand cmd = new OleDbCommand(String.Format("SELECT TOP 1 DataPath FROM CoursenotimeDataPath WHERE CourseId = {0}", Request.QueryString["CourseId"]), Con);
            try
            {
                Con.Open();
                ThePath = cmd.ExecuteScalar().ToString();
                //if (ThePath != string.Empty)
                //    ThePath = MapPath(DB.CourseNoTimeFileDir + ThePath);
                ThePath = DB.CourseNoTimeFileDir + ThePath;

                TextReader TR = new StreamReader(ThePath);
                RetData = TR.ReadToEnd();
                TR.Close();
                TR.Dispose();

            }
            catch (Exception ex)
            {
                RetData = ex.Message;
            }
            Con.Close();
        }

        return HttpUtility.HtmlDecode(RetData);
    }
Exemple #26
0
    public static List<String> GetAllDomainSuffixes()
    {
        if(Helper.allDomainSuffixes == null || Helper.allDomainSuffixes.Count == 0)
        {
            allDomainSuffixes = new List<String>();

            StreamReader reader = new StreamReader(  HttpRuntime.AppDomainAppPath + "/App_Code/DataScience/allDomainSuffixes.txt");

            String line = null;
            while(true)
            {
                line = reader.ReadLine();
                if(line == null){
                    break;
                }

                if(!line.StartsWith("."))
                {
                    continue;
                }

                allDomainSuffixes.Add(line.Split(' ', '\t')[0]);

            }
            reader.Close();
        }
        return allDomainSuffixes;
    }
Exemple #27
0
    /// <summary>
    /// Get the syntax string from the wiki
    /// </summary>
    /// <param name="page">The name of the function you wish to look up</param>
    /// <returns>The function syntax string</returns>
    public string GetSyntaxString(string page)
    {
        WebRequest request = WebRequest.Create("http://wiki.multitheftauto.com/wiki/" + page);
        HttpWebResponse response;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch
        {
            return "Error";
        }
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string strHTML = reader.ReadToEnd();

        int iStartIndex = strHTML.IndexOf(@"<!-- PLAIN TEXT CODE FOR BOTS |") + (@"<!-- PLAIN TEXT CODE FOR BOTS |").Length;
        int iEndIndex = strHTML.IndexOf(@"|-->");

        if (iEndIndex <= iStartIndex)
            return "Error";

        string strSyntax = strHTML.Substring(iStartIndex, iEndIndex - iStartIndex);

        reader.Close();
        dataStream.Close();
        response.Close();

        return strSyntax;
    }
    public static string GetIPTCData_1(String imageurl)
    {
        string data;
        data = "img=" + imageurl;
        byte[] byteArray = Encoding.UTF8.GetBytes(data);
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8081/www/google/testimgmd5.php");
        httpWebRequest.ContentType = "application/x-www-form-urlencoded";
        httpWebRequest.ContentLength = byteArray.Length;
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "*/*";
        httpWebRequest.Headers.Add("Authorization", "Basic reallylongstring");

        //Get the stream that holds request data by calling the GetRequestStream method.
        Stream dataStream = httpWebRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        //Send the request to the server by calling GetResponse. This method returns an object containing the server's response. The returned WebResponse object's type is determined by the scheme of the request's URI
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            string md5content = streamReader.ReadToEnd();
            streamReader.Close();
            return md5content;
        }
    }
    public static void GetConfig(ref string NrIP, ref string NmLastUser, ref string SnPreEtiq, ref string NrTmpAtv)
    {
        if (File.Exists("LogosConfig.txt"))
        {
            StreamReader objReader = new StreamReader("LogosConfig.txt");
            NrIP = objReader.ReadLine();

            if (objReader.EndOfStream == false)
            {
                NmLastUser = objReader.ReadLine();
            }

            if (objReader.EndOfStream == false)
            {
                SnPreEtiq = objReader.ReadLine();
            }

            if (objReader.EndOfStream == false)
            {
                NrTmpAtv = objReader.ReadLine();
            }

            objReader.Close();
        }
    }
        public ManageyourEnergy()
        {
            int i = 0;
            int j = 0;
            int T = 0;
            long e = 0, r = 0, n = 0;
            long[] v = null;

            StreamReader sRead = new StreamReader(new FileStream(@"E:\Practice\GCJ\file\1.in", FileMode.Open));
            StreamWriter sWrite = new StreamWriter(new FileStream(@"E:\Practice\GCJ\file\1.out", FileMode.OpenOrCreate));
            T = Convert.ToInt32(sRead.ReadLine());

            for (i = 0; i < T; i++)
            {
                string[] tmp = sRead.ReadLine().Split(' ');
                e = Convert.ToInt64(tmp[0]);
                r = Convert.ToInt64(tmp[1]);
                n = Convert.ToInt64(tmp[2]);
                v = new long[n];
                tmp = sRead.ReadLine().Split(' ');
                for (j = 0; j < n; j++)
                {
                    v[j] = Convert.ToInt64(tmp[j]);
                }
                sWrite.WriteLine("Case #{0}: {1}", i + 1, calMax(e, r, n, v));
            }

            sRead.Close();
            sWrite.Close();
        }
Exemple #31
0
 public static string Read(string path)
 {
     var reader = new StreamReader(path);
     var s = reader.ReadToEnd();
     reader.Close();
     return s;
 }
Exemple #32
0
        public bool LoadConfigFile(out String errMsg)
        {
            StreamReader file = null;

            try
            {
                file = new StreamReader(configFile);
                XmlSerializer reader   = new XmlSerializer(typeof(Config));
                Config        __config = (Config)reader.Deserialize(file);
                __instance = __config;
                file.Close();
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                file?.Close();
                return(false);
            }
            errMsg = String.Empty;
            return(true);
        }
        /// <summary>
        /// Reads an object instance from an XML file.
        /// <para>Object type must have a parameterless constructor.</para>
        /// </summary>
        /// <typeparam name="T">The type of object to read from the file.</typeparam>
        /// <returns>Returns a new instance of the object read from the XML file.</returns>
        public static T ReadFromXmlFile <T>() where T : new()
        {
            if (!File.Exists(FilePath))
            {
                var data = new List <Booking>();
                SkrivXmlFile(data);
            }

            TextReader reader = null;

            try
            {
                var serializer = new XmlSerializer(typeof(T));
                reader = new StreamReader(FilePath);
                return((T)serializer.Deserialize(reader));
            }
            finally
            {
                reader?.Close();
            }
        }
Exemple #34
0
        /// <inheritdoc />
        public void ReadInput()
        {
            StreamReader reader = null;

            try
            {
                reader = new StreamReader($"Days/{GetType().Name}/input.txt");
                while (!reader.EndOfStream)
                {
                    inputs.Add(reader.ReadLine());
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                reader?.Close();
            }

            // turn every line into a chemical reaction
            foreach (string line in inputs)
            {
                List <Chemical> chemicals = line.Replace(" => ", ", ")                         // replace "=>" with "," so inputs are one line of comma separated chems
                                            .Split(',')                                        // split into an array of amounts and names
                                            .Select(s => s.Trim())                             // trim whitespace
                                            .Select(c => new Chemical()                        // create chemical from amount and name
                {
                    Amount = int.Parse(c.Split(' ')[0].Trim()),
                    Name   = c.Split(' ')[1].Trim()
                }).ToList();

                Reactions.Add(new Reaction()
                {
                    Output = chemicals.Last(),
                    Input  = chemicals.Take(chemicals.Count - 1).ToList()
                });
            }
        }
Exemple #35
0
        public void OpenFile(object sender, RoutedEventArgs e)
        {
            sortInfo.Arrays.Clear();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            List <int>     lst            = new List <int>();

            openFileDialog.Filter           = "TXT (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog.InitialDirectory = Environment.CurrentDirectory;
            if (openFileDialog.ShowDialog() == true)
            {
                StreamReader reader = null;
                try
                {
                    reader = new StreamReader(openFileDialog.FileName);
                    string   file   = reader.ReadToEnd();
                    string[] arrStr = file.Split(' ', '\n');
                    int      a;
                    foreach (string elem in arrStr)
                    {
                        if (Int32.TryParse(elem, out a))
                        {
                            lst.Add(a);
                        }
                        //else
                        //{
                        //    MessageBox.Show("Файл містить некоректні дані");
                        //    return;
                        //}
                    }
                    sortInfo.Arrays.Add(new MyArray <int>(lst.ToArray()));
                    ArrNumberCB.Items.Add(sortInfo.Arrays.Count);
                    ArrayChange();
                }
                catch { MessageBox.Show("Некоректний файл"); }
                finally
                {
                    reader?.Close();
                }
            }
        }
Exemple #36
0
        public UInt16 port;               //                     //组播端口
//

//
        /// <summary>
//
        /// LoadConfigFile
//
        /// </summary>
//
        /// <param name="errMsg"></param>
//
        /// <returns></returns>
//
        public bool LoadConfigFile(out String errMsg)
//
        {
//
            StreamReader file = null; //

//
            try
//
            {
//
                file = new StreamReader(configFile);                      //
//
                XmlSerializer reader = new XmlSerializer(typeof(Config)); //
//
                Config __config = (Config)reader.Deserialize(file);       //
//
                __instance = __config;                                    //
//
                file.Close();                                             //
//
            }
//
            catch (Exception ex)
//
            {
//
                errMsg = ex.Message; //
//
                file?.Close();       //
//
                return(false);       //
//
            }
//
            errMsg = String.Empty; //
//
            return(true);          //
//
        }
Exemple #37
0
        private void LoadGameBtn_Click(object sender, EventArgs e)
        {
            var fileDialog = new OpenFileDialog();

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                StreamReader stream = null;
                try
                {
                    stream = new StreamReader(fileDialog.FileName);
                    InputFacade.LoadGame(stream);
                }
                catch (SecurityException)
                {
                    AddToTrackingLog(ProgramLocalization.GameLoadingFailed);
                }
                finally
                {
                    stream?.Close();
                }
            }
        }
Exemple #38
0
        public static List <string> ReadFileByLine(string fileFullPath)
        {
            //1、StreamReader只用来读字符串。
            //2、StreamReader可以用来读任何Stream,包括FileStream也包括NetworkStream,MemoryStream等等。
            //3、FileStream用来操作文件流。可读写,可字符串,也可二进制。
            //重要的区别是,StreamReader是读者,用来读任何输入流;FileStream是文件流,可以被读,被写
            var          resultList = new List <string>();
            FileStream   aFile      = null;
            StreamReader sr         = null;

            try
            {
                aFile = new FileStream(fileFullPath, FileMode.Open);
                sr    = new StreamReader(aFile);
                var strLine = sr.ReadLine();
                while (strLine != null)
                {
                    resultList.Add(strLine);
                    strLine = sr.ReadLine();
                }
                return(resultList);
            }
            catch (IOException)
            {
                return(resultList);
            }
            finally
            {
                try
                {
                    sr?.Close();
                    aFile?.Close();
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
        /// <summary>
        /// Если был передан обыкновенный текстовый файл
        /// </summary>
        private SourceFile GetTxt(string filename)
        {
            StreamReader reader = null;
            string       text   = null;

            try
            {
                reader = new StreamReader(filename, Encoding.Default);
                text   = reader.ReadToEnd();
                reader.Close();
            }
            catch (Exception ex)
            {
                _errorList.Add(ex);
            }
            finally
            {
                reader?.Close();
                reader?.Dispose();
            }
            return(new SourceFile(text, null, Path.GetFileName(filename)));
        }
Exemple #40
0
        public string SendRequest(string methodName, object o = null)
        {
            StreamWriter streamWriter = null;
            StreamReader streamReader = null;
            var          result       = String.Empty;

            try
            {
                var webRequest = (HttpWebRequest)WebRequest.Create($"{baseApiAddress}{token}/{methodName}");
                webRequest.Method = "POST";

                if (o != null)
                {
                    var jsonText = JsonConvert.SerializeObject(o, Formatting.None, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    });

                    webRequest.ContentType = "application/json";
                    using (streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                    {
                        streamWriter.Write(jsonText);
                    }
                }

                var response = (HttpWebResponse)webRequest.GetResponse();
                using (streamReader = new StreamReader(response.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e);
            }
            streamWriter?.Close();
            streamReader?.Close();

            return(result);
        }
Exemple #41
0
        /// <summary>
        /// Disconnecting will leave TelnetClient in an unusable state.
        /// </summary>
        public void Disconnect()
        {
            try
            {
                // Blow up any outstanding tasks
                _internalCancellation.Cancel();

                // Both reader and writer use the TcpClient.GetStream(), and closing them will close the underlying stream
                // So closing the stream for TcpClient is redundant but it means we're triple sure.
                _tcpReader?.Close();
                _tcpWriter?.Close();
                _tcpClient?.Close();
            }
            catch (Exception ex)
            {
                TraceError($"{nameof(Disconnect)} error: {ex}");
            }
            finally
            {
                OnConnectionClosed();
            }
        }
Exemple #42
0
        public static string ReadHttpWebResponse(HttpWebResponse HttpWebResponse)
        {
            Stream       stream       = null;
            StreamReader streamReader = null;

            try
            {
                stream       = HttpWebResponse.GetResponseStream();
                streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                return(streamReader.ReadToEnd());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                streamReader?.Close();
                stream?.Close();
                HttpWebResponse?.Close();
            }
        }
Exemple #43
0
        /// <summary>
        /// Загрузка из файла
        /// </summary>
        public static JObject Load(string fileName)
        {
            FileStream   fs = null;
            StreamReader sr = null;

            try
            {
                fs = new FileStream(fileName, FileMode.Open);
                sr = new StreamReader(fs);
                return(JObject.Parse(sr.ReadToEnd()));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(null);
            }
            finally
            {
                sr?.Close();
                fs?.Close();
            }
        }
Exemple #44
0
        public static T Load <T>(string fileName)
        {
            FileStream   fs = null;
            StreamReader sr = null;

            try
            {
                fs = new FileStream(fileName, FileMode.Open);
                sr = new StreamReader(fs);
                return(JsonConvert.DeserializeObject <T>(sr.ReadToEnd()));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(default(T));
            }
            finally
            {
                sr?.Close();
                fs?.Close();
            }
        }
Exemple #45
0
        public void Dispose()
        {
            if (!_isDisposed)
            {
                _isDisposed = true;
                _cancellationSource.Cancel();
                if (_localProcess != null)
                {
                    _localProcess.Exited -= OnProcessExited;
                }
                _localProcess?.Close();

                _stdoutWriter?.Close();
                _processReader?.Close();
                _processError?.Close();

                _localProcess  = null;
                _stdoutWriter  = null;
                _processReader = null;
                _processError  = null;
            }
        }
Exemple #46
0
        /// <summary>
        /// Если был передан обыкновенный текстовый файл
        /// </summary>
        private SourceFile GetTxt(string filename)
        {
            StreamReader reader = null;
            string       text   = null;

            try
            {
                reader = new StreamReader(filename, Encoding.Default);
                text   = reader.ReadToEnd();
                reader.Close();
            }
            catch (Exception ex)
            {
                // MessageBox.Show($"Проблема при открытии файла вопросов: {ex.Message}");
            }
            finally
            {
                reader?.Close();
                reader?.Dispose();
            }
            return(new SourceFile(text, null, Path.GetFileName(filename)));
        }
Exemple #47
0
        }     // ValidateXmlFile()

        #endregion // PUBLIC METHODS

        //// ---------------------------------------------------------------------

        #region PRIVATE METHODS
        /// <summary>
        /// Reads an XML schema form the specified file.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns>A <see cref="XmlSchema"/>.</returns>
        private static XmlSchema ReadXmlSchema(string filename)
        {
            var          fi     = new FileInfo(filename);
            StreamReader sr     = null;
            XmlSchema    schema = null;

            try
            {
                sr     = new StreamReader(fi.FullName);
                schema = XmlSchema.Read(sr, ValidationCallBack);
            }
            catch (Exception ex)
            {
                Log.Error("Error reading schema file", ex);
            }
            finally
            {
                sr?.Close();
            } // finally

            return(schema);
        } // ReadXmlSchema()
Exemple #48
0
        public static string ReadFile(string fullName)
        {
            //  Encoding code = Encoding.GetEncoding(); //Encoding.GetEncoding("gb2312");
            string temp = fullName.MapPath().ReplacePath();
            string str  = "";

            if (!File.Exists(temp))
            {
                return(str);
            }
            StreamReader sr = null;

            try
            {
                sr  = new StreamReader(temp);
                str = sr.ReadToEnd(); // 读取文件
            }
            catch { }
            sr?.Close();
            sr?.Dispose();
            return(str);
        }
Exemple #49
0
        /// <summary>
        /// Read input data into line-separated in groups
        /// </summary>
        static List <Tuple <int, string> > ReadInput(string filename)
        {
            StreamReader reader     = null;
            var          input      = "";
            var          data       = new List <Tuple <int, string> >();
            var          group      = new StringBuilder();
            var          groupCount = 0;

            try
            {
                using (reader = new StreamReader(filename))
                {
                    while ((input = reader.ReadLine()) != null)
                    {
                        if (input.Length == 0)
                        {
                            data.Add(new Tuple <int, string>(groupCount, group.ToString()));
                            group.Clear();
                            groupCount = 0;
                            continue;
                        }

                        groupCount++;
                        group.Append(input);
                    }

                    if (group.Length > 0)
                    {
                        data.Add(new Tuple <int, string>(groupCount, group.ToString()));
                    }

                    return(data);
                }
            }
            finally
            {
                reader?.Close();
            }
        }
Exemple #50
0
        string GetHtml(string uri)//请求指定url取得返回html数据
        {
            Stream       rsp = null;
            StreamReader sr  = null;

            try
            {
                WebRequest http = WebRequest.Create(uri);
                rsp = http.GetResponse().GetResponseStream();
                sr  = new StreamReader(rsp, Encoding.UTF8);
                return("成功:" + sr.ReadToEnd());
            }
            catch (Exception ex)
            {
                return("失败:" + ex.Message);
            }
            finally
            {
                sr?.Close();
                rsp?.Close();
            }
        }
        /// <summary>
        /// Reads an object instance from an Json file.
        /// <para>Object type must have a parameterless constructor.</para>
        /// </summary>
        /// <typeparam name="T">The type of object to read from the file.</typeparam>
        /// <param name="filePath">The file path to read the object instance from.</param>
        /// <returns>Returns a new instance of the object read from the Json file.</returns>
        public static T ReadFromJsonFile <T>(string filePath) where T : new()
        {
            TextReader reader = null;
            T          result;

            try
            {
                reader = new StreamReader(filePath);
                var fileContents = reader.ReadToEnd();
                result = JsonConvert.DeserializeObject <T>(fileContents);
            }
            catch (Exception ex)
            {
                result = new T();
            }
            finally
            {
                reader?.Close();
            }

            return(result);
        }
Exemple #52
0
        public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            Stream       stream       = null;
            StreamReader streamReader = null;

            try
            {
                stream = rsp.GetResponseStream();
                if ("gzip".Equals(rsp.ContentEncoding, StringComparison.OrdinalIgnoreCase))
                {
                    stream = new GZipStream(stream, CompressionMode.Decompress);
                }
                streamReader = new StreamReader(stream, encoding);
                return(streamReader.ReadToEnd());
            }
            finally
            {
                streamReader?.Close();
                stream?.Close();
                rsp?.Close();
            }
        }
Exemple #53
0
        private void OpenFile()
        {
            char         sep = ';';
            FileStream   fs  = null;
            StreamReader sr  = null;

            try
            {
                fs = new FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read);
                sr = new StreamReader(fs, Encoding.Default);

                DataTable dt = new DataTable();
                dt.Columns.Add("ItemName", typeof(string));
                dt.Columns.Add("InventoryNumber", typeof(string));

                string[] line;
                while (!sr.EndOfStream)
                {
                    DataRow dr = dt.NewRow();
                    line = sr.ReadLine().Split(sep);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        dr[i] = line[i];
                    }
                    dt.Rows.Add(dr);
                }
                dgvPreview.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sr?.Close();
                fs?.Close();
            }
        }
Exemple #54
0
        public static Soft GetSoft(int id, String token)
        {
            Soft   soft = null;
            String url  = String.Format("{0}{1}{2}.json?access_token={3}", domain, GetUrl, id, token);

            String       json   = null;
            Stream       stream = null;
            StreamReader reader = null;

            try
            {
                HttpWebResponse response = Tools.HttpWebResponseUtility.CreateGetHttpResponse(url, null, 30000,
                                                                                              "WinForm", null);
                stream = response.GetResponseStream();
                reader = new StreamReader(stream);
                json   = reader.ReadToEnd();
            }
            catch (System.Net.WebException e)
            {
                MessageBox.Show(e.Message, "更新异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
            finally
            {
                reader?.Close();
                stream?.Close();
            }

            NetResult result = JsonHelper.DeserializeJsonToObject <NetResult>(json);

            if (result.Status == "succ")
            {
                JObject item = result.Data as JObject;
                soft = new Soft(item);
            }

            return(soft);
        }
Exemple #55
0
        private void CallbackMethod(object sender, OpenReadCompletedEventArgs e)
        {
            Stream       reply  = null;
            StreamReader reader = null;

            try
            {
                reply  = e.Result;
                reader = new StreamReader(reply, Encoding.UTF8);

                var line  = reader.ReadToEnd();
                var match = Regex.Match(line, LyricsMarkPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                if (match.Success)
                {
                    LyricText = match.Groups[1].Value;
                    LyricText = HttpUtility.HtmlDecode(LyricText);
                }

                if (LyricText.Length > 0)
                {
                    CleanLyrics();
                }
                else
                {
                    LyricText = NotFound;
                }
            }
            catch
            {
                LyricText = NotFound;
            }
            finally
            {
                reader?.Close();
                reply?.Close();
                Complete = true;
            }
        }
        private async Task <JToken> GetRootTokenAsync()
        {
            StreamReader fileReader = null;

            try
            {
                using (fileReader = File.OpenText(_configPath))
                {
                    using (JsonTextReader reader = new JsonTextReader(fileReader))
                    {
                        return(await JToken.ReadFromAsync(reader));
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                throw new FileNotFoundException("Configuration file is not found", e);
            }
            finally
            {
                fileReader?.Close();
            }
        }
Exemple #57
0
        static Graph LoadFromFile(string filename)
        {
            var reader = default(StreamReader);
            var input  = default(string);
            var data   = new List <string>();

            try
            {
                using (reader = new StreamReader(filename))
                {
                    while ((input = reader.ReadLine()) != null)
                    {
                        data.Add(input);
                    }

                    return(ParseGraph(data));
                }
            }
            finally
            {
                reader?.Close();
            }
        }
Exemple #58
0
        /// <inheritdoc />
        public void ReadInput()
        {
            StreamReader reader = null;

            try
            {
                reader = new StreamReader($"Days/{GetType().Name}/input.txt");
                while (!reader.EndOfStream)
                {
                    inputs.Add(reader.ReadLine());
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                reader?.Close();
            }

            program = inputs[0].Split(',').Select(long.Parse).ToList();
        }
Exemple #59
0
        private void DisposeClient()
        {
            if (_connection is null)
            {
                return;
            }

            if (_cancellationTokenSource != null && _cancellationTokenSource.Token.CanBeCanceled)
            {
                _cancellationTokenSource.Cancel();
            }

            _streamReader?.Close();
            _streamReader?.Dispose();
            _streamReader = null;

            _streamWriter?.Close();
            _streamWriter?.Dispose();
            _streamWriter = null;

            _connection?.Dispose();
            _connection = null;
        }
Exemple #60
0
        static List <long> LoadNumbers(string filename)
        {
            var numbers = new List <long>();
            var reader  = default(StreamReader);
            var input   = default(string);

            try
            {
                using (reader = new StreamReader(filename))
                {
                    while ((input = reader.ReadLine()) != null)
                    {
                        numbers.Add(long.Parse(input));
                    }

                    return(numbers);
                }
            }
            finally
            {
                reader?.Close();
            }
        }