本文整理汇总了C#中System.IO.StreamReader类的典型用法代码示例。如果您正苦于以下问题:C# StreamReader类的具体用法?C# StreamReader怎么用?C# StreamReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StreamReader类属于System.IO命名空间,在下文中一共展示了StreamReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ResetIp
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";
}
}
示例2: Main
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();
}
示例3: GetDealClosingCostTypesFromDeepBlue
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;
}
示例4: Start
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();
}
}
示例5: sendMessage
private void sendMessage()
{
MailAddress adresa = new MailAddress("[email protected]");
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("[email protected]", "[email protected]", předmětTextBox.Text, textZprávyTextBox.Text + log);
}
else
{
zpráva = new MailMessage("[email protected]", "[email protected]", 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);
}
示例6: AllFieldsEmptyTest
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 );
}
}
示例7: Main
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();
}
示例8: Delete
/// <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);
}
}
示例9: ReadStudentsInfoFromFile
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();
}
}
}
示例10: ReadToken
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);
}
}
示例11: EatWhitespace
private void EatWhitespace(StreamReader sr)
{
while (char.IsWhiteSpace(sr.PeekChar()))
{
sr.ReadChar();
}
}
示例12: Decrypt
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.");
}
}
示例13: Download
public string Download(Uri uri)
{
using(var reader = new StreamReader(uri.LocalPath))
{
return reader.ReadToEnd();
}
}
示例14: Up
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);
}
}
}
示例15: SaveTileBackgroundImage
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();
}
}
}