C# (CSharp) Class System.IO. StreamReader Code Examples

C# (CSharp) System.IO.StreamReader - 30 examples found. These are the top rated real world C# (CSharp) examples of class System.IO.StreamReader extracted from open source projects. You can rate examples to help us improve the quality of examples
Inheritance: TextReader
Example #1
0
        static void Main(string[] args)
        {
            var m_Config = new ServerConfig
            {
                Port = 911,
                Ip = "Any",
                MaxConnectionNumber = 1000,
                Mode = SocketMode.Tcp,
                Name = "CustomProtocolServer"
            };

            var m_Server = new CustomProtocolServer();
            m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
            m_Server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
                    socketStream.Write(requestNameData, 0, requestNameData.Length);
                    var data = Encoding.ASCII.GetBytes(currentMessage);
                    socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
                    socketStream.Write(data, 0, data.Length);
                    socketStream.Flush();

                   // Console.WriteLine("Sent: " + currentMessage);

                    var line = reader.ReadLine();
                    //Console.WriteLine("Received: " + line);
                    //Assert.AreEqual(currentMessage, line);
                }

                

                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }

            Console.ReadLine();
        }
Example #2
0
 public void Start(string[] args)
 {
     registry = new Registry();
     if (!registry.Register(this))
     {
         Console.WriteLine("Error registering service.");
         return;
     }
     Console.WriteLine("Registered service.");
     try
     {
         TcpClient tcpclient = new TcpClient();
         if (args.Count() != 2)
             throw new Exception("Argument must contain a publishing ip and port. call with: 127.0.0.1 12345");
         tcpclient.Connect(args[0], Int32.Parse(args[1]));
         StreamReader sr = new StreamReader(tcpclient.GetStream());
         string data;
         while ((data = sr.ReadLine()) != null)
         {
             Console.WriteLine("Raw data: " + data);
             if (RawAisData != null)
                 RawAisData(data);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message + e.StackTrace);
         Console.WriteLine("Press enter");
         Console.ReadLine();
     }
 }
Example #3
0
 public static List<DeepBlue.Models.Entity.DealClosingCostType> GetDealClosingCostTypesFromDeepBlue(CookieCollection cookies)
 {
     // Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc
     List<DeepBlue.Models.Entity.DealClosingCostType> dealClosingCostTypes = new List<DeepBlue.Models.Entity.DealClosingCostType>();
     // Send the request
     string url = HttpWebRequestUtil.GetUrl("Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc");
     HttpWebResponse response = HttpWebRequestUtil.SendRequest(url, null, false, cookies, false, HttpWebRequestUtil.JsonContentType);
     if (response.StatusCode == System.Net.HttpStatusCode.OK) {
         using (Stream receiveStream = response.GetResponseStream()) {
             // Pipes the stream to a higher level stream reader with the required encoding format.
             using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) {
                 string resp = readStream.ReadToEnd();
                 if (!string.IsNullOrEmpty(resp)) {
                     JavaScriptSerializer js = new JavaScriptSerializer();
                     FlexigridData flexiGrid = (FlexigridData)js.Deserialize(resp, typeof(FlexigridData));
                     foreach (Helpers.FlexigridRow row in flexiGrid.rows) {
                         DeepBlue.Models.Entity.DealClosingCostType dealClosingType = new DeepBlue.Models.Entity.DealClosingCostType();
                         dealClosingType.DealClosingCostTypeID = Convert.ToInt32(row.cell[0]);
                         dealClosingType.Name = Convert.ToString(row.cell[1]);
                         dealClosingCostTypes.Add(dealClosingType);
                     }
                 }
                 else {
                 }
                 response.Close();
                 readStream.Close();
             }
         }
     }
     return dealClosingCostTypes;
 }
        public void AllFieldsEmptyTest()
        {
            using( var stream = new MemoryStream() )
            using( var reader = new StreamReader( stream ) )
            using( var writer = new StreamWriter( stream ) )
            using( var parser = new CsvParser( reader ) )
            {
                writer.WriteLine( ";;;;" );
                writer.WriteLine( ";;;;" );
                writer.Flush();
                stream.Position = 0;

                parser.Configuration.Delimiter = ";;";
                parser.Configuration.HasHeaderRecord = false;

                var row = parser.Read();
                Assert.IsNotNull( row );
                Assert.AreEqual( 3, row.Length );
                Assert.AreEqual( "", row[0] );
                Assert.AreEqual( "", row[1] );
                Assert.AreEqual( "", row[2] );

                row = parser.Read();
                Assert.IsNotNull( row );
                Assert.AreEqual( 3, row.Length );
                Assert.AreEqual( "", row[0] );
                Assert.AreEqual( "", row[1] );
                Assert.AreEqual( "", row[2] );

                row = parser.Read();
                Assert.IsNull( row );
            }
        }
Example #5
0
 private void sendMessage()
 {
     MailAddress adresa = new MailAddress("cendrb@gmail.com");
     MailMessage zpráva;
     if (logFile)
     {
         string log;
         using (StreamReader reader = new StreamReader(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Info", "Log", "logStatusBaru.log")))
         {
             log = reader.ReadToEnd();
         }
         if (log.Length > 50000)
             log.Remove(50000);
         zpráva = new MailMessage("adisinfoapp@gmail.com", "cendrb@gmail.com", předmětTextBox.Text, textZprávyTextBox.Text + log);
     }
     else
     {
         zpráva = new MailMessage("adisinfoapp@gmail.com", "cendrb@gmail.com", předmětTextBox.Text, textZprávyTextBox.Text);
     }
     SmtpClient klient = new SmtpClient();
     klient.Host = "smtp.gmail.com";
     klient.Port = 465;
     klient.EnableSsl = true;
     //klient.Send(zpráva);
 }
Example #6
0
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public void Delete(string fileName)
        {
            try
            {
                string uri = ftpURI + fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + "  文件名:" + fileName);
            }
        }
        public static void Main()
        {
            var url = new Uri(ApiUrl + "?auth-id=" + AuthenticationID + "&auth-token=" + AuthenticationToken);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
                writer.Write(RequestPayload);

            using (var response = request.GetResponse())
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var rawResponse = reader.ReadToEnd();
                Console.WriteLine(rawResponse);

                // Suppose you wanted to use Json.Net to pretty-print the response (delete the next two lines if not):
                // Json.Net: http://http://json.codeplex.com/
                dynamic parsedJson = JsonConvert.DeserializeObject(rawResponse);
                Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));

                // Or suppose you wanted to deserialize the json response to a defined structure (defined below):
                var candidates = JsonConvert.DeserializeObject<CandidateAddress[]>(rawResponse);
                foreach (var address in candidates)
                    Console.WriteLine(address.DeliveryLine1);
            }

            Console.ReadLine();
        }
        private object ReadToken(StreamReader sr)
        {
            EatWhitespace(sr);

            char c = sr.ReadChar();
            switch (c)
            {
                case '{':
                    return ReadDict(sr);
                case '/':
                    {
                        if (sr.PeekChar() == '/')
                        {
                            sr.ReadLine();
                            return null;
                        }
                        else
                        {
                            return ReadString(sr, c);
                        }
                    }

                default:
                    return ReadString(sr, c);
            }
        }
        private static void ReadStudentsInfoFromFile(string filePath, SortedDictionary<string, SortedSet<Student>> courses)
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line = reader.ReadLine();
                while (line != string.Empty && line != null)
                {
                    string[] data = line.Split('|');
                    string firstName = data[0].Trim();
                    string lastName = data[1].Trim();
                    string courseName = data[2].Trim();

                    if (courses.ContainsKey(courseName))
                    {
                        courses[courseName].Add(new Student(firstName, lastName));
                    }
                    else
                    {
                        courses[courseName] = new SortedSet<Student>();
                        courses[courseName].Add(new Student(firstName, lastName));
                    }

                    line = reader.ReadLine();
                }
            }
        }
        public static string Decrypt(string sourceData)
        {
            // set key and initialization vector values
              byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
              byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
              try
              {
            // convert data to byte array
            byte[] encryptedDataBytes =
               Convert.FromBase64String(sourceData);

            // get source memory stream and fill it
            MemoryStream tempStream =
               new MemoryStream(encryptedDataBytes, 0,
              encryptedDataBytes.Length);

            // get decryptor and decryption stream
            DESCryptoServiceProvider decryptor =
               new DESCryptoServiceProvider();
            CryptoStream decryptionStream =
               new CryptoStream(tempStream,
              decryptor.CreateDecryptor(key, iv),
              CryptoStreamMode.Read);

            // decrypt data
            StreamReader allDataReader =
               new StreamReader(decryptionStream);
            return allDataReader.ReadToEnd();
              }
              catch
              {
            throw new StringEncryptorException(
               "Unable to decrypt data.");
              }
        }
 private void EatWhitespace(StreamReader sr)
 {
     while (char.IsWhiteSpace(sr.PeekChar()))
     {
         sr.ReadChar();
     }
 }
 public string Download(Uri uri)
 {
     using(var reader = new StreamReader(uri.LocalPath))
     {
         return reader.ReadToEnd();
     }
 }
Example #13
0
		public override void Up()
		{
			AddTables();

			using (var sm = new StreamReader(GetType().Assembly.GetManifestResourceStream("DVS.Database.Databases.DVS_DB.Version2.SystemData.sql")))
			{
				var systemDataScript = sm.ReadToEnd();
				if (!String.IsNullOrEmpty(systemDataScript))
					AddSql(systemDataScript);
			}

			Sql(@"create trigger dbo.tr_PopGeolocation
					on dbo.AppraiserServiceAreas
					for insert, update
					as
					BEGIN
					update a 
					set [GeoLocation] = geography::STGeomFromText('POINT(' + CAST([a].[Longitude] AS VARCHAR(20)) + ' ' + CAST([a].[Latitude] AS VARCHAR(20)) + ')', 4326)
					from dbo.AppraiserServiceAreas a
					join inserted i on i.id = a.id
					END");

			if (DbConfigManager.IsAddTestData)
			{
				using (var sm = new StreamReader(GetType().Assembly.GetManifestResourceStream("DVS.Database.Databases.DVS_DB.Version2.TestData.sql")))
				{
					var testDataScript = sm.ReadToEnd();
					if (!String.IsNullOrEmpty(testDataScript))
						AddSql(testDataScript);
				}
			}
		}
Example #14
0
        private static void SaveTileBackgroundImage(TileViewModel model)
        {
            string xamlCode;

            using (var tileStream = Application.GetResourceStream(new Uri("/WP7LiveTileDemo;component/Controls/CustomTile.xaml", UriKind.Relative)).Stream)
            {
                using (var reader = new StreamReader(tileStream))
                {
                    xamlCode = reader.ReadToEnd();
                }
            }

            var control = (Control)XamlReader.Load(xamlCode);
            control.DataContext = model;

            var bitmap = new WriteableBitmap(173, 173);

            bitmap.Render(control, new TranslateTransform());

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = store.CreateFile(TileBackgroundPath))
                {
                    bitmap.Invalidate();
                    bitmap.SaveJpeg(stream, 173, 173, 0, 100);
                    stream.Close();
                }
            }
        }
Example #15
0
        public GeoIP()
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://freegeoip.net/xml/");
                request.Proxy = null;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseString = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(responseString);

                WANIP = doc.SelectSingleNode("Response//Ip").InnerXml.ToString();
                Country = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//CountryName").InnerXml.ToString())) ? doc.SelectSingleNode("Response//CountryName").InnerXml.ToString() : "Unknown";
                CountryCode = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//CountryCode").InnerXml.ToString())) ? doc.SelectSingleNode("Response//CountryCode").InnerXml.ToString() : "-";
                Region = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//RegionName").InnerXml.ToString())) ? doc.SelectSingleNode("Response//RegionName").InnerXml.ToString() : "Unknown";
                City = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//City").InnerXml.ToString())) ? doc.SelectSingleNode("Response//City").InnerXml.ToString() : "Unknown";
            }
            catch
            {
                WANIP = "-";
                Country = "Unknown";
                CountryCode = "-";
                Region = "Unknown";
                City = "Unknown";
            }
        }
Example #16
0
 public static string Post(this HttpListenerRequest request,  string str)
 {
     using (StreamReader stream = new StreamReader(request.InputStream))
     {
         return stream.ReadToEnd();
     }
 }
Example #17
0
        private void ResetIp()
        {
            try
            {
                textBoxIP.Text = "";
                var req = (HttpWebRequest)WebRequest.Create("http://canyouseeme.org");
                var resp = (HttpWebResponse)req.GetResponse();
                string x = new StreamReader(resp.GetResponseStream()).ReadToEnd();
                //  input type="hidden" name="IP" value="41.28.175.2"/>
                string[] sepd = x.Split(new char[] { '<' });
                foreach (string s in sepd)
                    if (s.Contains("input type=\"hidden\" name=\"IP\""))
                    {
                        string[] spdbyspace = s.Split(new char[] { ' ' });
                        foreach (string sen in spdbyspace)
                            if (sen.Contains("value"))
                            {
                                string[] spd_by_qoute = sen.Split(new char[] { '"' });
                                this.CurrentExIp = spd_by_qoute[1];
                                textBoxIP.Text = this.CurrentExIp;

                                this.ExIpDetetected = true;
                                return;
                            }
                    }
            }
            catch (Exception z)
            {
                textBoxIP.Text = "No internet";
            }
        }
Example #18
0
        public Shader(GraphicsDevice dev, string name)
        {
            this.dev = dev;
            string code;
            using (var file = new StreamReader(FileSystem.Open("cg{0}{1}.fx".F(Path.DirectorySeparatorChar, name))))
                code = file.ReadToEnd();
            effect = Tao.Cg.Cg.cgCreateEffect(dev.Context, code, null);

            if (effect == IntPtr.Zero)
            {
                var err = Tao.Cg.Cg.cgGetErrorString(Tao.Cg.Cg.cgGetError());
                var results = Tao.Cg.Cg.cgGetLastListing(dev.Context);
                throw new InvalidOperationException(
                    "Cg compile failed ({0}):\n{1}".F(err, results));
            }

            technique = Tao.Cg.Cg.cgGetFirstTechnique(effect);
            if (technique == IntPtr.Zero)
                throw new InvalidOperationException("No techniques");
            while (Tao.Cg.Cg.cgValidateTechnique(technique) == 0)
            {
                technique = Tao.Cg.Cg.cgGetNextTechnique(technique);
                if (technique == IntPtr.Zero)
                    throw new InvalidOperationException("No valid techniques");
            }
        }
Example #19
0
        private void DlgTips_Load(object sender, EventArgs e)
        {   
            try
            {
                string strxml = "";
                using (StreamReader streamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Johnny.Kaixin.WinUI.Resources.Versions.config")))
                {
                    strxml = streamReader.ReadToEnd();
                }

                XmlDocument objXmlDoc = new XmlDocument();
                objXmlDoc.LoadXml(strxml);

                if (objXmlDoc == null)
                    return;

                DataView dv = GetData(objXmlDoc, "ZrAssistant/Versions");

                for (int ix = 0; ix < dv.Table.Rows.Count; ix++)
                {
                    _versionList.Add(dv.Table.Rows[ix][0].ToString(), dv.Table.Rows[ix][1].ToString());
                    cmbVersion.Items.Add(dv.Table.Rows[ix][0].ToString());
                }

                chkNeverDisplay.Checked = Properties.Settings.Default.NeverDisplay;
                cmbVersion.SelectedIndex = 0;
                SetTextValue();
                btnOk.Select();
            }
            catch (Exception ex)
            {
                Program.ShowMessageBox("DlgTips", ex);
            }
        }
 private string ReadFromFSLocation(string path)
 {
     using (StreamReader sr = new StreamReader(path))
     {
         return sr.ReadToEnd().Trim();
     }
 }
Example #21
0
        public static void ConvertFormat(string strInputFile, string strOutputFile)
        {
            StreamReader sr = new StreamReader(strInputFile);
            StreamWriter sw = new StreamWriter(strOutputFile);
            string strLine = null;

            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();

                string[] items = strLine.Split();
                foreach (string item in items)
                {
                    int pos = item.LastIndexOf('[');
                    string strTerm = item.Substring(0, pos);
                    string strTag = item.Substring(pos + 1, item.Length - pos - 2);

                    sw.WriteLine("{0}\t{1}", strTerm, strTag);
                }
                sw.WriteLine();
            }

            sr.Close();
            sw.Close();
        }
Example #22
0
        // TODO: hack
        public RubyIO(RubyContext/*!*/ context, StreamReader reader, StreamWriter writer, string/*!*/ modeString)
            : this(context) {
            _mode = ParseIOMode(modeString, out _preserveEndOfLines);
            _stream = new DuplexStream(reader, writer);

            ResetLineNumbersForReadOnlyFiles(context);
        }
Example #23
0
        public static void Extract(Category category)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Extract");
            if(!Directory.Exists(path))
                Directory.CreateDirectory(path);

            pset.Clear();
            pdic.Clear();
            string downPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Down", category.Name);
            string fileName = string.Format(@"{0}\{1}.txt", path, category.Name);

            StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
            for (int i = category.DownPageCount; i >= 1; i--)
            {
                string htmlFileName = string.Format(@"{0}\{1}.html", downPath, i);
                if (!File.Exists(htmlFileName))
                    Logger.Instance.Write(string.Format("{0}-{1}.html-not exist", category.Name, i));
                StreamReader sr = new StreamReader(htmlFileName, Encoding.UTF8);
                string text = sr.ReadToEnd();
                sr.Close();

                var action = CreateAction(category.Type);
                if (action == null) continue;

                Extract(text, sw, category.Name,category.DbName, action);
            }
            sw.Close();

            Console.WriteLine("{0}:Extract Data Finished!", category.Name);
        }
Example #24
0
 public void Init()
 {
     srStrokes = new StreamReader(opt.StrokesFileName);
     srTypes = new StreamReader(opt.StrokesTypesFileName);
     srCedict = new StreamReader(opt.CedictFileName);
     swOut = new StreamWriter(opt.OutFileName);
 }
Example #25
0
        /// Read long numbers and initialize parameters
        /// A0 - The right particle of the first part of the number
        /// A1 - The left particle of the first part of the number
        /// B0 - The right particle of the second part of the number
        /// B1 - The left particle of the second part of the number
        /// K - Middle of the numbers
        /// N - Number of bits
        public static void Read(out BigInteger A0, out BigInteger A1,
                                out BigInteger B0, out BigInteger B1,
                                out int K, out int N)
        {
            using (StreamReader sr = new StreamReader("test.txt"))
            {
                string a, a0, a1, b, b0, b1;
                a = sr.ReadLine();
                b = sr.ReadLine();

                K = a.Length / 2;
                N = a.Length;

                // making strings to parse
                a0 = a.Substring(0, K);
                a1 = a.Substring(K);
                b0 = b.Substring(0, K);
                b1 = b.Substring(K);

                A0 = BigInteger.Parse(a1);
                A1 = BigInteger.Parse(a0);
                B0 = BigInteger.Parse(b1);
                B1 = BigInteger.Parse(b0);
            }

        }
Example #26
0
        public BoxInfo(int clientID, string fileName)
        {
            StreamReader sr = new StreamReader(fileName);

            sr.ReadLine();// burn the headings

            for (int x = 0; x < 28; x++)
            {
                myCompartments[x] = new Compartment();
            }

            string[] dataLine;

            while (!sr.EndOfStream)
            {
                dataLine = sr.ReadLine().Split(',');
                int curID = int.Parse (dataLine[0].Trim());

                if (curID == clientID)
                { //this dataline is for this client
                    int compartmentNum = int.Parse(dataLine[1]);
                    int hour = int.Parse(dataLine[2]);
                    int minute = int.Parse(dataLine[3]);
                    string pills = dataLine[4].Trim();
                    myCompartments[compartmentNum-1].hour = hour;
                    myCompartments[compartmentNum-1].minute = minute;
                    myCompartments[compartmentNum-1].pills = pills;
                }
           
            }


        }
		public string GetFileContent(string filePath)
		{
			if (string.IsNullOrWhiteSpace(filePath))
			{
				throw new ArgumentException(
					string.Format(CommonStrings.ErrorMessage_FilePathNotSpecified, filePath),
					"filePath"
				);
			}

			string content;
			string fullFilePath = _textContentDirectoryPath.TrimEnd('/') + "/" + filePath;
			string physicalFilePath = GetPhysicalFilePath(fullFilePath);

			try
			{
				using (FileStream fileStream = File.OpenRead(physicalFilePath))
				using (var reader = new StreamReader(fileStream))
				{
					content = reader.ReadToEnd();
				}
			}
			catch (FileNotFoundException)
			{
				throw new FileNotFoundException(
					string.Format(CommonStrings.ErrorMessage_FileNotFound, filePath));
			}
			catch (DirectoryNotFoundException)
			{
				throw new FileNotFoundException(
					string.Format(CommonStrings.ErrorMessage_FileNotFound, filePath));
			}

			return content;
		}
        /// <summary>
        /// loads a xml from the web server
        /// </summary>
        /// <param name="_url">URL of the XML file</param>
        /// <returns>A XmlDocument object of the XML file</returns>
        public static XmlDocument LoadXml(string _url)
        {
            var xmlDoc = new XmlDocument();
            
            try
            {
                while (Helper.pingForum("forum.mods.de", 10000) == false)
                {
                    Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
                    System.Threading.Thread.Sleep(15000);
                }

                xmlDoc.Load(_url);
            }
            catch (XmlException)
            {
                while (Helper.pingForum("forum.mods.de", 100000) == false)
                {
                    Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
                    System.Threading.Thread.Sleep(15000);
                }

                WebClient client = new WebClient(); ;
                Stream stream = client.OpenRead(_url);
                StreamReader reader = new StreamReader(stream);
                string content = reader.ReadToEnd();

                content = RemoveTroublesomeCharacters(content);
                xmlDoc.LoadXml(content);
            }

            return xmlDoc;
        }
        private void ChangeCopyright()
        {
            UpdateLabel("searching for rotmg version display string");
            Dictionary<string, string> files = new Dictionary<string, string>();
            string filetext = String.Empty;

            foreach (string path in this.files)
            {
                using (StreamReader rdr = new StreamReader(File.Open(path, FileMode.Open)))
                {
                    filetext = rdr.ReadToEnd();
                    if (filetext.Contains(ROTMG_VERSION_TEXT))
                    {
                        UpdateLabel("request found!");
                        files.Add(path, filetext);
                    }
                }
            }

            foreach (var file in files)
            {
                UpdateLabel("replacing version text");
                filetext = file.Value.Replace(ROTMG_VERSION_TEXT, "<font color='#00CCFF'>Fabiano Swagger of Doom</font> #{VERSION}.{MINORVERSION}");
                filetext = filetext.Replace("{MINOR}", "{MINORVERSION}");
                using (StreamWriter wtr = new StreamWriter(file.Key, false))
                    wtr.Write(filetext);
            }
            UpdateLabel("Version Display: Done!");
        }
Example #30
0
 private static string ReadContentFromResult(HttpWebResponse response)
 {
     using (var reader = new StreamReader(response.GetResponseStream()))
     {
         return reader.ReadToEnd();
     }
 }